Go array
Go arrays differ slightly from those in other languages, and the specifics are as follows:
var variableName [length]DataType
- An array is a fixed-length sequence of the same data type.
- Array Length Must be a Constant: The length of an array must be a constant expression and cannot be changed once the array is defined.
- Array Length as Part of the Type: The length of an array is part of its type. Therefore, var a[5]int and var a[10]int are of different types.
- Zero-Based Indexing: Array indices start at 0, and the last element's index is len-1, where len is the length of the array.
- Index Out of Bounds Panic: If an index is outside the bounds of the array, it triggers an access violation, causing a panic.
- Value Type: Arrays are value types. Assigning or passing an array to a function copies the entire array, not a pointer. Thus, modifying the value of a copy does not change the original array.
- Pointer to an entire Array: *[n]T, where T is the type of the elements in the array, and n is the length of the array
- Pointer to an Array Element: [n]*T, where T is the type of the element, and n is the number of pointers
Array Initialization
One-dimensional Array:
var a1 [5]int = [5]int{1, 2, 3, 4} //Uninitialized elements have a value of 0
var a2 = [5]int{1, 2, 3, 4, 5}
var a3 = [...]int{1, 2, 3, 4, 5, 6} //Automatically determine array length via initialization values
var a4 = [5]string{3: "hi", 4: "cregend"} //Initialize elements using subscript indices
var a5 = [...]struct {
name string
age int
}{
{"cregend", 10}, //Element type can be omitted (type inference)
{"synfun", 20},
}
Multi-dimensional Array:
var a1 [2][3]int = [2][3]int{{1, 2, 3}, {4, 5, 6}}
var a2 [3][2]int = [...][2]int{{1, 1}, {2, 2}, {3, 3}} //Cannot use "..." starting from the second dimension
Array Traversal:
length := len(a)
for i := 0; i < length; i++ {
//...
}
for key, val := range a {
//...
}
Take a break
πππ γJade Dynasty EP46γAn exciting confrontation between two beauties: Lu Xueqi vs Jin Ping'er