Arrays
Arrays in Go are fixed-size collections of elements of the same type. They are useful for storing a known number of items. The table below contains information on patterns, characteristics, operations and more!
Key Points
- Array size is fixed and part of its type:
[3]intand[4]intare different types - Arrays are value types - assignment and function parameters create copies
- Use
[...]to let compiler infer size from initialization - Zero value of array elements depends on the element type
- Slices are almost always preferred over arrays for flexibility
- Arrays are useful for fixed-size buffers or when you need value semantics
Declaring and Using an Array
package main
import "fmt"
func main() {
// Declare an array of integers with a size of 5
var numbers [5]int
// Initialize the array with values
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
// Print the array
fmt.Println("Array:", numbers)
// Access individual elements
fmt.Println("First element:", numbers[0])
fmt.Println("Second element:", numbers[1])
// Get the length of the array
fmt.Println("Length of array:", len(numbers))
}Array: [10 20 30 40 50]
First element: 10
Second element: 20
Length of array: 5Array Declaration Patterns
| Pattern | Example | Description |
|---|---|---|
var name [size]type | var a [5]int | Declare array with zero values |
[size]type{values} | [3]int{1, 2, 3} | Declare and initialize with values |
[...]type{values} | [...]int{1, 2, 3, 4} | Size inferred from values |
[size]type{index: value} | [5]int{2: 10, 4: 20} | Initialize specific indices |
[size][size]type | [3][2]int{{1,2},{3,4},{5,6}} | Multi-dimensional arrays |
Array Operations
| Operation | Syntax | Example | Description |
|---|---|---|---|
| Access element | array[index] | a[0] | Get or set element at index |
| Get length | len(array) | len(a) | Returns the number of elements |
| Iterate | for i, v := range array | for i, v := range a | Loop through index and value |
| Compare | array1 == array2 | a == b | Arrays of same type/size are comparable |
| Copy | b := a | b := a | Creates a copy (value type) |
| Pass to function | func(arr [5]int) | process(a) | Passed by value (copied) |
Array vs Slice
| Feature | Array | Slice |
|---|---|---|
| Size | Fixed at compile time | Dynamic, can grow/shrink |
| Declaration | [5]int | []int |
| Memory | Value type (copied) | Reference type (points to array) |
| Type identity | Size is part of type | Size not part of type |
| Use case | Known, fixed number of elements | Variable number of elements |
| Performance | Stack allocated, predictable | Heap allocated, flexible |