In the previous lesson, we learned how to use range with integers. Now let's explore one of its most common use cases: iterating over slices.
When you use range with a slice, it returns two values on each iteration: the index and the value at that index.
names := []string{"Goku", "Vegeta", "Gohan"}
for index, value := range names {
fmt.Println(index, value)
}
// Output:
// 0 Goku
// 1 Vegeta
// 2 Gohan
The first variable receives the index (position), and the second receives the actual value from the slice.
Often you only care about the values, not the indices. You can use the blank identifier _ to ignore the index:
fruits := []string{"apple", "banana", "orange"}
for _, fruit := range fruits {
fmt.Println("I like", fruit)
}
// Output:
// I like apple
// I like banana
// I like orange
This is the most common pattern when working with slices - you typically care more about the values than their positions.
Sometimes you only need the index. You can simply omit the second variable:
colors := []string{"red", "green", "blue"}
for index := range colors {
fmt.Println("Color at position", index)
}
// Output:
// Color at position 0
// Color at position 1
// Color at position 2
You can use the index to access or modify slice elements:
scores := []int{85, 92, 78}
for i := range scores {
scores[i] = scores[i] + 5 // Add 5 to each score
fmt.Println("Updated score:", scores[i])
}
// Output:
// Updated score: 90
// Updated score: 97
// Updated score: 83
Important: The value variable in a range loop is a copy, not a reference to the original element:
numbers := []int{1, 2, 3}
// This won't modify the slice
for _, num := range numbers {
num = num * 2 // Only modifies the copy
}
fmt.Println(numbers) // Still [1, 2, 3]
// This will modify the slice
for i := range numbers {
numbers[i] = numbers[i] * 2 // Modifies the actual element
}
fmt.Println(numbers) // Now [2, 4, 6]
Ranging over an empty slice is perfectly safe - the loop simply won't execute:
empty := []string{}
for _, item := range empty {
fmt.Println(item) // Never executes
}
fmt.Println("Done!") // This runs normally
For this challenge, create a function called sumPowerLevels that accepts a parameter levels (a slice of integers: []int).
The function should:
range to iterate over the sliceThe function signature is:
func sumPowerLevels(levels []int) {
// Your code here
}
For example, calling sumPowerLevels([]int{9000, 8500, 8000}) should print:
25500