Variable declaration
- var variable name = type expression
- var Variable Name Type
- var variable name 1, variable name 2, Type 3 Variable Name
- var variable name 1, variable name 2, 3 = variable name expression 1, expression 2, expression 3
Short variable declaration
- Variable name: = expression
- 1 variable name, variable name 2: = expression 1, expression 2
Pointer variable declaration
- was int * p
- var p = & T, p: = & T // T represents a variable name
- p := new(type)、var p = new(type)
First, declare and initialize an array
var array [5]int
// specified length
array := [5]int{10, 20, 30, 40, 50}
// specified length and literals
array := [...]int{10, 20, 30, 40, 50}
// compiler automatically calculate the length
array := [5]int{1: 10, 2: 20}
// the specified array length and partial value
Two, slice declare and initialize
slice := make([]string, 5)
// use make
the specified length
slice := make([]int, 3, 5)
// specified length and capacity, length> = Capacity
slice := []int{10, 20, 30}
// use literal
slice := []string{99: ""}
Use index declare and specify the initialization value
Third, create a nil
slice
Fourth, create a 空
slice
slice := make([]int, 0)
// Create an empty integer make use sliced
slice := []int{}
// Create an empty literal use slice sliced integer
V. mapping declare and initialize
dict := make(map[string]int)
dict := map[string]string{"Red": "#da1337", "Orange": "#e95a22"}
dict := map[int][]string{}
dict := map[string]int{}
Sixth, declare a nil
map
var colors map[string]string