This is a creation in Article, where the information may have evolved or changed.
First Program
package mainimport "fmt"var s = "hello" //全局变量func main() {fmt.Println(s, "world")}
go run hello.go
Output
hello world
2.1 Variables
Go uses the keyword var
to define the variable, and the type information is placed behind the variable name and initialized to zero, as follows:
var s string var x intvar ( //批量声明a intf float64x string)
There's a more concise way to define inside a function. :=
func main() { s := "string" //局部变量}
Variable assignment, two variables can be exchanged directly
var i, j inti, j = j, i
Note: The compiler will error if the variable defined inside the function is not used.
declared and not used
2.2 Constants
With the keyword const
definition, the constant value must be a numeric value that can be determined during compilation.
const Pi
Enumeration iota
, which starts from 0 by the number of rows, and if it const
is re-calculated again starting from 0.
const (Sunday = iota // 0Monday // 1Tuesday // 2Wednesday // 3Thursday // 4Friday // 5Saturday // 6)
2.3 Types
Go includes the following basic types:
- Boolean type: BOOL.
- Integral type: int8, Byte, int16, int, uint, uintptr, etc.
- Floating point types: float32, float64.
- Plural type: complex64, complex128.
- Character: String.
- Character type: Rune.
- Fault type: Error.
There are also complex types: slice, map, and so on.
2.4 Key Words