Working with arrays
Arrays are fixed-size data structures. There is no way to resize an array or to create an array using a variable as its size (in other words, [n]int
is valid only if n
is a constant integer). Because of this, arrays are useful to represent an object with a fixed number of elements, such as a SHA256 hash, which is 32 bytes.
The zero-value for an array has zero-values for every element of the array. For instance, [5]int
is initialized with five integers, all 0. A string array will have empty strings.
Creating arrays and passing them around
This recipe shows how you can create arrays and pass array values to functions and methods. We will also talk about the effects of passing arrays as values.
How to do it...
- Create arrays using a fixed size:
var arr [2]int // Array of 2 ints
You can also declare an array using an array literal without specifying its size:
x := [...]int{1,2} // Array of 2 ints
You can specify array indexes similar to defining a map...