Go > Collections > Arrays and Slices > Defining arrays
Defining and Using Arrays in Go
This example demonstrates how to define and use arrays in Go. Arrays are fixed-size sequences of elements of the same type. Learn how to declare, initialize, and access array elements.
Basic Array Declaration and Initialization
This code snippet shows how to declare an array named `numbers` of type `int` with a fixed size of 5. Each element is then initialized with a specific value. The `fmt.Println` function is used to print the entire array and also to access and print a specific element using its index. Array indices start at 0.
package main
import "fmt"
func main() {
// Declare an array of 5 integers.
var numbers [5]int
// Initialize array elements.
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
// Print the array.
fmt.Println(numbers)
// Access array elements by index.
fmt.Println("Element at index 2:", numbers[2])
}
Array Initialization with Literals
This example demonstrates array initialization using array literals. The `colors` array is declared as an array of 3 strings and initialized directly with values. The `fruits` array uses ellipsis `...` which allows the compiler to infer the size of the array based on the number of elements in the literal.
package main
import "fmt"
func main() {
// Declare and initialize an array with values.
colors := [3]string{"red", "green", "blue"}
// Print the array.
fmt.Println(colors)
// Using ellipsis to let the compiler infer the size
fruits := [...]string{"apple", "banana", "orange"}
fmt.Println(fruits)
fmt.Println("Length of fruits array:", len(fruits))
}
Iterating Over an Array
This snippet demonstrates two ways to iterate over an array. The first uses a traditional `for` loop with an index. The second uses the `range` keyword, which provides both the index and the value of each element in the array. The `range` approach is generally preferred for its readability and conciseness.
package main
import "fmt"
func main() {
numbers := [5]int{1, 2, 3, 4, 5}
// Iterate over the array using a for loop.
for i := 0; i < len(numbers); i++ {
fmt.Printf("numbers[%d] = %d\n", i, numbers[i])
}
// Iterate using range
for index, value := range numbers {
fmt.Printf("numbers[%d] = %d\n", index, value)
}
}
Real-Life Use Case
Arrays are useful for representing fixed-size data structures like RGB color values (e.g., `[3]uint8{255, 0, 0}` for red), representing coordinates (e.g., `[2]float64{10.5, 20.3}`), or storing a fixed set of configuration parameters.
Best Practices
range
keyword for readability.
When to use them
Use arrays when you know the exact number of elements you'll need and the size won't change. Arrays are allocated contiguously in memory, making access very fast.
Memory footprint
The memory footprint of an array is determined at compile time and is equal to the size of one element multiplied by the number of elements. For example, an array of 5 integers ([5]int) takes up 5 * 4 = 20 bytes on a 32-bit system or 5 * 8 = 40 bytes on a 64-bit system.
Alternatives
Slices are a more flexible alternative to arrays in Go. Slices are dynamically sized and can grow or shrink as needed. They are generally preferred over arrays unless you have a specific reason to use a fixed-size data structure.
Pros
Cons
FAQ
-
What is the difference between an array and a slice in Go?
An array has a fixed size defined at compile time, while a slice is a dynamically sized segment of an array or a pointer to an underlying array. Slices are more flexible and commonly used in Go. -
How do I determine the length of an array?
You can use the `len()` function to get the length of an array. For example: `length := len(myArray)`. -
Can I change the size of an array after it is created?
No, arrays in Go have a fixed size. You cannot change the size of an array after it has been declared. If you need a dynamically sized collection, use a slice.