The example in this article summarizes the common ways that the go language creates and initializes arrays. Share to everyone for your reference. The specific analysis is as follows:
The syntax for the Go language is flexible, and the following shows several ways to create and initialize an array:
Copy Code code as follows:
Array initialization in various ways
Func arraySliceTest0201 () {
Create an array (declaration length)
var array1 = [5]int{1, 2, 3}
Fmt. Printf ("Array1---type:%t \ n", array1)
Rangeintprint (array1[:])
Create an array (without declaring the length)
var array2 = [...] Int{6, 7, 8}
Fmt. Printf ("Array2---type:%t \ n", array2)
Rangeintprint (array2[:])
Create an array slice
var array3 = []int{9, 10, 11, 12}
Fmt. Printf ("Array3---type:%t \ n", Array3)
Rangeintprint (ARRAY3)
Creates an array (declaring the length) and initializes only some of its elements
var array4 = [5]string{3: "Chris", 4: "Ron"}
Fmt. Printf ("Array4---type:%t \ n", Array4)
Rangeobjprint (array4[:])
Creates an array (without declaring the length) and initializes only some of its elements, the length of which is determined by the initialized element
var array5 = [...] String{3: "Tom", 2: "Alice"}
Fmt. Printf ("Array5---type:%t \ n", Array5)
Rangeobjprint (array5[:])
Creates an array slice and initializes only some of its elements, and Len of the array slice determines according to the initialized element
var array6 = []string{4: "Smith", 2: "Alice"}
Fmt. Printf ("Array6---type:%t \ n", Array6)
Rangeobjprint (ARRAY6)
}
Output an integral array of slices
Func rangeintprint (Array []int) {
For I, V: = range Array {
Fmt. Printf ("index:%d value:%d\n", I, v)
}
}
Output string Array slice
Func rangeobjprint (Array []string) {
For I, V: = range Array {
Fmt. Printf ("index:%d value:%s\n", I, v)
}
}
I hope this article will help you with your go language program.