This is a creation in Article, where the information may have evolved or changed.
Examples of array definition formats:
var a [2]intfmt println ( a ) b := [ 2 " int { 2 3 } fmt.Println(b)
Output: [0 0][2 3]
You can also omit the array length, which the compiler automatically calculates:
a := [...] int { 5 6 7 8 }
You can also use index initialization:
a := [...]int{9:1}fmt.Println(a)
Output: [0 0 0 0 0 0 0 0 0 1]
It is important to note that the array length is also part of the array type, so different array types have different arrays in go for the value type, that is, the time to pass the array variable is full copy, if you want to pass the reference, will use the Go special type: Slice, the following will refer to the array can be used = = or! = To compare the use of new to create an array, the array pointer is returned:
a := new([10]int)
The bottom is an array, and multiple slice can point to the same array at the bottom. You can specify the initial length and capacity, noting that the length and capacity concepts are different, length refers to the length of the array that the slice uses to hold the data, and the capacity is the total length of the underlying array to allocate contiguous memory. When you give the slice append element, so that the length exceeds the capacity, go will create a new array with a capacity of twice times the current capacity, and copy the data in.
var S0 [" int //is similar to defining an array, except that you do not need to specify the length fmt.Println(s0) //[]a:= [Ten]int{0,1,2,3,4,5,6,7,8,9} //Declare an arrays1 := a [ 5 : 10 " //intercepts some part of the array fmt println ( s1 ) Span class= "com" style= "Color:rgb (147,161,161)" >//[5 6 7 8 9] s2 := a [ 5 :] //interception starts at an index to the end of the array fmt println ( s2 ) Span class= "com" style= "Color:rgb (147,161,161)" >//[5 6 7 8 9] s3 := a [: 5 " //interception starts from the beginning of the array to an index fmt println ( s3 ) Span class= "com" style= "Color:rgb (147,161,161)" >//[0 1 2 3 4] s4 := make([]int,3,10) //创建一个类型为整型数组,长度为3,容量为10的sliceFMT.Println(Len(S4),Cap(S4),S4) //3 [0 0 0]S5:= []int{1,2,3,4} //definition and initialization of slicefmt.Println(s5) //[1,2,3,4]s6 := a [:] //points to the entire array of a fmt println ( s6 ) Span class= "com" style= "Color:rgb (147,161,161)" >//[0,1,2,3,4,5,6,7,8,9]