Ever wished you could keep your data super organized like a librarian with an obsession for alphabetization? Well, arrays in Golang do just that! They let you store multiple values in a single, tidy container.
In this guide, we’ll cover:
- What arrays are and how they work.
- How to declare, initialize, and manipulate arrays.
- Common pitfalls and best practices.
What is an Array?
An array is a fixed-size collection of elements of the same type. Think of it like a row of lockers — each one can hold a value, but you can’t change the total number of lockers after you create them.
Example: Declaring an Array
package main
import "fmt"
func main() {
var numbers [5]int // An array of 5 integers
fmt.Println(numbers) // [0 0 0 0 0]
}
Output:
[0 0 0 0 0]
Arrays in Go automatically initialize with zero values.
Initializing an Array
You can set values at the time of declaration:
func main() {
numbers := [3]int{10, 20, 30}
fmt.Println(numbers)
}
Output:
[10 20 30]
Accessing and Modifying Array Elements
You can access elements using their index (starting from 0):
func main() {
colors := [3]string{"red", "green", "blue"}
fmt.Println(colors[1]) // green
colors[1] = "yellow"
fmt.Println(colors) // [red yellow blue]
}
The len()
Function
Need to know the length of an array? Use len()
:
func main() {
arr := [4]int{1, 2, 3, 4}
fmt.Println(len(arr)) // 4
}
Looping Through an Array
Using for
Loop
func main() {
nums := [3]int{100, 200, 300}
for i := 0; i < len(nums); i++ {
fmt.Println(nums[i])
}
}
Using range
func main() {
nums := [3]int{100, 200, 300}
for index, value := range nums {
fmt.Println("Index:", index, "Value:", value)
}
}
Multidimensional Arrays (Arrays in Arrays!)
Need more complexity? Use multidimensional arrays!
func main() {
matrix := [2][3]int{{1, 2, 3}, {4, 5, 6}}
fmt.Println(matrix)
}
Output:
[[1 2 3] [4 5 6]]
Think of it as a spreadsheet with rows and columns.
Common Pitfalls
- Fixed Size: Once declared, the size of an array cannot be changed.
- Zero-Based Indexing: Accessing an index out of bounds causes a runtime error.
- Prefer Slices for Flexibility: Slices (dynamic arrays) are often more useful.
Arrays in Go are great for storing fixed-size collections of data. While powerful, they come with limitations—so if you need flexibility, consider slices instead. Now go forth and store your data like a pro! Happy coding!
0 Comments