Arrays in Go: Complete Beginner’s Guide with Examples
Welcome to your first real data structure in Go! 🎉 Arrays are like the building blocks of programming. Think of them as a row of boxes where you can store things in order.
What is an Array? (Real Life Analogy)
Imagine you have a parking lot with exactly 10 parking spaces. Each space can hold one car, and you know exactly where each car is parked.
- Parking Lot = Array
- Parking Spaces = Array positions (numbered 0, 1, 2, …, 9)
- Cars = Data you store
Or think of a bookshelf with exactly 5 shelves. Each shelf can hold one book.
Key Points:
- Arrays have a fixed size (you can’t add more parking spaces)
- All items must be the same type (all cars, or all books)
- You can access any item instantly by its position number
Creating Arrays in Go
Simple Arrays (Like a Row of Boxes)
// Create an array for 5 test scores
var scores [5]int
// Put scores in each box
scores[0] = 85 // First box
scores[1] = 92 // Second box
scores[2] = 78 // Third box
scores[3] = 90 // Fourth box
scores[4] = 88 // Fifth box
What just happened?
var scores [5]int= “Create 5 boxes for integers”scores[0] = 85= “Put 85 in the first box”- Arrays start counting from 0, not 1!
Creating Arrays with Initial Values
// Create and fill the array at the same time
var grades [4]int = [4]int{90, 85, 88, 92}
// Shorter way (Go figures out the size)
marks := [...]int{95, 87, 91, 83, 89}
// Even shorter (only works sometimes)
shoppingList := [...]string{"milk", "bread", "eggs", "apples"}
Real Life Example:
// Like organizing your weekly temperatures
var weeklyTemp [7]int = [7]int{25, 28, 30, 27, 26, 24, 29}
// Monday=25°, Tuesday=28°, Wednesday=30°, etc.
Reading from Arrays
Getting Values from Boxes
fruits := [...]string{"apple", "banana", "orange", "grape", "mango"}
firstFruit := fruits[0] // "apple"
thirdFruit := fruits[2] // "orange"
lastFruit := fruits[4] // "mango"
Think of it like:
fruits[0]= “What’s in the first box?”fruits[2]= “What’s in the third box?”
How Many Items?
numbers := [...]int{10, 20, 30, 40, 50}
count := len(numbers) // count = 5
fruits := [...]string{"apple", "banana", "orange"}
fruitCount := len(fruits) // fruitCount = 3
len() tells you how many boxes are in your array.
Changing Array Values
Updating What’s in the Boxes
// Start with some colors
colors := [...]string{"red", "blue", "green", "yellow"}
// Change blue to purple
colors[1] = "purple"
// Now colors = ["red", "purple", "green", "yellow"]
Real Life Example - Grocery Shopping:
shoppingList := [...]string{"milk", "bread", "eggs", "apples"}
// Oh wait, I need oranges instead of apples
shoppingList[3] = "oranges"
// Now shoppingList = ["milk", "bread", "eggs", "oranges"]
Looping Through Arrays
Method 1: The Traditional Way
scores := [...]int{85, 92, 78, 90, 88}
for i := 0; i < len(scores); i++ {
fmt.Printf("Score %d: %d\n", i+1, scores[i])
}
Output:
Score 1: 85
Score 2: 92
Score 3: 78
Score 4: 90
Score 5: 88
Method 2: The Go Way (Easier!)
fruits := [...]string{"apple", "banana", "orange", "grape"}
for position, fruit := range fruits {
fmt.Printf("Box %d has: %s\n", position, fruit)
}
Output:
Box 0 has: apple
Box 1 has: banana
Box 2 has: orange
Box 3 has: grape
Real Life Examples
Example 1: Student Grades
package main
import "fmt"
func main() {
// Store 5 students' grades
grades := [...]int{85, 92, 78, 90, 88}
fmt.Println("=== Student Grades ===")
// Print all grades
for i, grade := range grades {
fmt.Printf("Student %d: %d points\n", i+1, grade)
}
// Calculate average
total := 0
for _, grade := range grades {
total += grade
}
average := total / len(grades)
fmt.Printf("Class Average: %d points\n", average)
}
Output:
=== Student Grades ===
Student 1: 85 points
Student 2: 92 points
Student 3: 78 points
Student 4: 90 points
Student 5: 88 points
Class Average: 86 points
Example 2: Grocery Shopping
package main
import "fmt"
func main() {
// Shopping list with prices
items := [...]string{"Milk", "Bread", "Eggs", "Apples", "Cheese"}
prices := [...]float64{2.50, 1.80, 3.20, 4.00, 5.50}
fmt.Println("=== Shopping List ===")
total := 0.0
for i := 0; i < len(items); i++ {
fmt.Printf("%s: $%.2f\n", items[i], prices[i])
total += prices[i]
}
fmt.Printf("Total Cost: $%.2f\n", total)
// Find the most expensive item
maxPrice := prices[0]
expensiveItem := items[0]
for i := 1; i < len(prices); i++ {
if prices[i] > maxPrice {
maxPrice = prices[i]
expensiveItem = items[i]
}
}
fmt.Printf("Most Expensive: %s ($%.2f)\n", expensiveItem, maxPrice)
}
Output:
=== Shopping List ===
Milk: $2.50
Bread: $1.80
Eggs: $3.20
Apples: $4.00
Cheese: $5.50
Total Cost: $17.00
Most Expensive: Cheese ($5.50)
Common Array Operations
Finding the Largest Number
func findLargest(numbers [5]int) int {
largest := numbers[0] // Start with first number
for i := 1; i < len(numbers); i++ {
if numbers[i] > largest {
largest = numbers[i]
}
}
return largest
}
// Usage
scores := [...]int{85, 92, 78, 90, 88}
highest := findLargest(scores) // highest = 92
Counting How Many Times Something Appears
func countOccurrences(arr [10]int, target int) int {
count := 0
for _, num := range arr {
if num == target {
count++
}
}
return count
}
// Usage
votes := [...]int{1, 2, 1, 1, 2, 1, 2, 1, 1, 2}
ones := countOccurrences(votes, 1) // ones = 6
twos := countOccurrences(votes, 2) // twos = 4
Arrays vs Real Life
| Array Concept | Real Life Example |
|---|---|
array[0] | First parking space |
array[1] | Second parking space |
len(array) | Total parking spaces |
| Fixed size | Limited parking lot |
| Same type | All cars (not cars and boats) |
Practice Time!
Try these exercises:
Exercise 1: Temperature Tracker
Create an array to store 7 days of temperatures and find:
- The hottest day
- The coldest day
- Average temperature
Exercise 2: Score Calculator
Create arrays for:
- Student names (strings)
- Their scores (integers)
- Calculate who has the highest score
Exercise 3: Inventory Counter
Create arrays for:
- Product names
- Stock quantities
- Find which product needs restocking (quantity < 5)
Important Notes
Arrays are Fixed Size
var numbers [5]int // Can only hold exactly 5 numbers
// You CANNOT add a 6th number to this array!
Start Counting from 0
fruits := [...]string{"apple", "banana", "orange"}
// fruits[0] = "apple" (first)
// fruits[1] = "banana" (second)
// fruits[2] = "orange" (third)
All Items Must Be Same Type
var scores [3]int = [3]int{85, 92, 78} // ✓ All integers
var mixed [3]interface{} // ✗ Don't do this yet
What’s Next?
Arrays are great, but they have limitations:
- Can’t grow bigger once created
- Can’t insert items in the middle easily
In the next lesson, we’ll learn about Slices - Go’s dynamic arrays that can grow and shrink!
Quick Quiz
- What does
len(array)tell you? - Why do arrays start at index 0?
- Can you change what’s stored in an array?
- What’s the difference between
[5]intand[...]int?
Remember: Arrays are like fixed parking lots. Great for when you know exactly how many spaces you need!