Overview
Arrays in Go are fixed-size collections of elements of the same type. Unlike C, Go arrays are always zero-initialized, eliminating garbage memory vulnerabilities.In Go, arrays are generally used when you need a fixed-size collection. For dynamic collections, use slices.
Zero Initialization
One of Go’s safety features is guaranteed zero initialization. When you declare an array without explicitly setting values, Go automatically initializes all elements to their zero value.Basic Array Declaration
Here’s how to declare and work with arrays in Go:arrays/main.go
Key Characteristics
Fixed Size
The size of an array is part of its type. An array of[5]int is a different type from [10]int.
The
len() function returns the length of the array, which is always the size specified at declaration.Multi-dimensional Arrays
Go supports multi-dimensional arrays for matrices and grids:When to Use Arrays
For most use cases, Go developers prefer slices over arrays because slices are more flexible and idiomatic.Zero Values by Type
| Type | Zero Value |
|---|---|
int, int8, int16, int32, int64 | 0 |
float32, float64 | 0.0 |
bool | false |
string | "" (empty string) |
| Pointer types | nil |
No ‘undefined’ errors. If you declare
var nums [5]int but don’t set values, Go initializes each element to 0. No garbage memory.