Go Arrays: Difference between revisions
Line 117: | Line 117: | ||
} | } | ||
</pre> | </pre> | ||
==Array Operators and Functions== | ==Array Operators and Functions== |
Revision as of 18:08, 24 August 2023
External
Internal
Overview
An array is a composite type that consists in a fixed-length, contiguous and numbered sequence of elements. All elements of an array have the same type. The type of the elements can be a Go built-in type, a user type or a pointer. *<type>
notation is used to declare a pointer array.
The compiler knows the length of the array and the type of its elements at compile time, so it knows how much space to allocate. The length of the array is part of the type name, arrays with different lengths are of different types, even if the element type is the same. Once an array is declared, its type and length cannot be changed.
Arrays are fast: data is maintain in continuous blocks of memory, which keeps them in the CPU caches longer. Index access and arithmetic is fast: the type information and the guarantee that all elements are of same type allows calculating "distance in memory" to find elements. The arrays are the internal data structures used both by slices and maps, and they are rarely used directly in Go code.
Arrays are Values
An array is a value in Go. It can be used in an assignment operation. The variable name denotes the entire array, thus an array can be assigned to other arrays of the same type, which is designated by the length and element type. When an array a2
is assigned to an array a1
, the values of a2
are copied across to a1
.
In Go, function arguments are passed by value. The fact that arrays are values also has implications on how arrays are passed between functions: by value. A copy of the entire array is made and placed on the stack, regardless of the array's size. For large arrays, this can have performance implications. That is why, passing pointers to arrays is preferred. As a general rule, array should not be used directly in code, use slices instead.
Declaration
The array type includes the size, enclosed in square brackets, followed by the element type. As mentioned above, different size arrays are different types, even if they have the same element type.
var a [7]int
The elements are initialized to zero value of the type the array is composed of, upon declaration:
println(a[0]) // displays 0
Literals
The array literals are predefined values that go into an array and they are used to initialize an array. The type ([3]int
) is specified as part of the array literal, so it does not have to be provided in the var
syntax, but it can be provided, redundantly.
var a = [3]int{7, 17, 37}
The length of the array, provided between square brackets, must match the number of elements in the literal, otherwise the compiler will indicate compilation error.
A better, alternative representation of the array literal uses [...]
to express that the size of the array will be given by the number of elements in the literal.
var a = [...]int{7, 17, 37} // the type of a is inferred to be [3]int
var b = [...]int{
5,
15,
25
}
Partial Initialization Literals
Go provides syntax for initializing just some of the elements with specified values, letting the compiler to initialize the rest with zero values:
a := [100]int{0:10, 1:20}
In the example above, the element 0 is initialized to 10, the element 1 is initialized to 20 and the rest are initialized to their zero value (0).
Initialization
The initialization with type inference, with a literal, can be used:
var a = [...]int{7, 17, 37}
Also, the short variable declaration can be used as well:
a := [...]int{7, 17, 37}
Empty Array
Operators
Indexing Operator []
Array elements are accessed using the indexing (subscript) operator. Indices are zero-based.
Iterating though Arrays
Use the range
keyword. range
allows to iterate by indices, values or both.
Iterate by indices:
for i := range a {
fmt.Printf("index: %d\n", i)
}
Iterate by values:
for _, e := range a {
fmt.Printf("element value: %d\n", e)
}
Iterate by both indices and values:
for i, e := range a {
fmt.Printf("index: %d, element value: %d\n", i, e)
}
TO DISTRIBUTE
Declaration
Short Declaration
The short declaration:
a := [3]int{1, 2, 3}
The short declaration is invalid for arrays if the length and type is not followed by the initialization literal { ... }, the initialization literal is required.
For the format above, there's redundancy in the requirement to specify the length of the array between square brackets and the length of the literal. The compiler can infer the length of the array from the literal, and the declaration is:
a := [...]int{1, 2, 3}
The literal can be specified "vertically":
a := [...]int{ 1, 2, 3, }
Array Operators and Functions
Indexing Operator
Indexing operator [] returns the value at the given position and can also be used to change the value at that position. Accesses are bound-checked and an attempt to access an element out of bounds produces a compile-time or runtime error:
Compile-time error:
./main.go:13: invalid array index 3 (out of bounds for 3-element array)
Runtime error:
panic: runtime error: index out of range
Array Length
len() returns the length of the array.
Iterating over Arrays
Multidimensional Arrays
TODO Go in Action page 84.