Arrays in Go
An array in Go is a collection of elements that all share the same data type. Arrays store multiple values in a single variable and are useful when you know the exact number of elements in advance.
Unlike slices, arrays in Go have a fixed size that cannot be changed after creation.
Declaring an Array
An array declaration includes the data type and the number of elements.
package main
import "fmt"
func main() {
var numbers [5]int
fmt.Println(numbers)
}
This creates an array of 5 integers.
All values are initialized to 0 by default.
Initializing an Array with Values
You can assign values to an array at the time of declaration.
package main
import "fmt"
func main() {
scores := [4]int{85, 90, 78, 88}
fmt.Println(scores)
}
Each value is stored at a specific position (index) in the array.
Accessing Array Elements
Array elements are accessed using index numbers.
Indexing in Go starts from 0.
package main
import "fmt"
func main() {
scores := [4]int{85, 90, 78, 88}
fmt.Println(scores[0])
fmt.Println(scores[2])
}
Here, scores[0] accesses the first element,
and scores[2] accesses the third element.
Updating Array Values
You can modify an array element by assigning a new value to its index.
package main
import "fmt"
func main() {
scores := [4]int{85, 90, 78, 88}
scores[1] = 95
fmt.Println(scores)
}
The value at index 1 is updated from 90 to 95.
Array Length
The len() function returns the total number of elements in an array.
package main
import "fmt"
func main() {
scores := [4]int{85, 90, 78, 88}
fmt.Println("Length:", len(scores))
}
The length of an array is fixed and part of its type definition.
Looping Through an Array
Arrays are commonly processed using loops.
package main
import "fmt"
func main() {
scores := [4]int{85, 90, 78, 88}
for i := 0; i < len(scores); i++ {
fmt.Println("Score:", scores[i])
}
}
This loop prints each element stored in the array.
Real-World Example: Daily Sales
Arrays are useful when handling fixed-size datasets, such as daily sales for a week.
package main
import "fmt"
func main() {
sales := [7]int{1200, 1500, 980, 1100, 1750, 1600, 1400}
total := 0
for i := 0; i < len(sales); i++ {
total += sales[i]
}
fmt.Println("Weekly Sales:", total)
}
This program calculates the total sales for a week using an array.
Important Rules About Arrays
- Arrays have a fixed size
- The size is part of the array’s type
- All elements must be the same data type
- Arrays are stored in contiguous memory
Arrays vs Other Data Structures
Arrays are efficient and simple, but they lack flexibility. When you need a dynamic size, Go provides slices, which are built on top of arrays.
What’s Next?
In the next lesson, you will learn about Slices in Go, which are more flexible and widely used than arrays in real-world applications.