Use a Go array when the number of elements is known and fixed. An array holds one element type in contiguous storage; its zero-based indices provide direct access. Both length and element type belong to its type, so [5]int and [4]int are different types. section 4.1 section 4.1.1
Declare an array with var to get zero-valued elements, or initialize it with a literal: values := [5]int{10, 20, 30} leaves the last two elements at zero. A literal can name particular indices. The [...] form lets the compiler determine the length, but an explicit length is safer when an unintended size would matter. section 4.1.1
Table 4.1 Different types of array declarations
| Format |
Description |
Example |
Result |
|---|---|---|---|
|
|
Array variable declaration |
|
|
|
|
Array literal with optional starting values |
|
|
|
|
Array literal with sparse values |
|
|
|
|
Array literal with automatic size |
|
|
Compare ordinary, partially initialized, indexed, and automatically sized declarations. section 4.1.1
For routine traversal, range supplies indices and, optionally, copies of the elements. Changing a range value does not change the array: use the index to assign to an element instead. An indexed for loop also works when traversal must run backward or skip elements. section 4.1.4
Copy a fixed set of values
Assigning one [5]string array to another copies all five elements into a separate array. The same rule applies to nested arrays: [2][2]int is an array of arrays, and grid[1][0] accesses an inner value. If the elements are pointers, assignment copies the pointers, so the two arrays can still refer to the same objects. section 4.1.5 section 4.1.6
An array passed to a function is copied in full. For a large fixed-size image array, passing a pointer avoids that copy, but changes through the pointer affect the original. Arrays cannot grow or shrink; when the number of items varies, use a slice instead. A slice expression can also make a slice backed by an existing array. section 4.1.7 section 4.1.8 section 4.2.6







































