Iterate Over a Slice
Lesson 9 of 21 in Coddy's Slices and Maps in Golang course.
Just like what we did with arrays, we can iterate over a slice using a for loop. Let's make an example that demonstrates this:
Suppose we have a slice like this:
str := []string{"Python","Golang","Rust","JavaScript","Haskell"}
for i := 0; i < len(str); i++ {
fmt.Println(i, str[i])
}Here we iterate from 0 to the length of the slice using the <strong>len()</strong> function and we will get the result:
0 Python
1 Golang
2 Rust
3 JavaScript
4 HaskellNothing new for us here, but let's use a new keyword called <strong>range</strong> which will allow us to iterate over the slice. The syntax should be like this:
for index, value := range str {
fmt.Println(index, value)
}In our example, <strong>range</strong> is used to iterate over the elements of the <strong>str</strong> slice, providing both the index and the value at that index in each iteration.
And we should get the same result as before:
0 Python
1 Golang
2 Rust
3 JavaScript
4 HaskellIf we don't need the index, we can omit it by using an underscore instead of a key:
for _, value := range str {
fmt.Println(value)
}
Challenge
EasyIn the given code, we define a slice of integer numbers.
- Using the
<strong>range</strong>keyword to iterate over the slice, check each number to determine if it's even - If a number is even, add it to a variable that will hold the sum of the even numbers
Try it yourself
package main
import "fmt"
func main() {
// Slice of 10 numbers Don't change this!
numbers := []int{45, 60, 3, 4, 5, 80, 7, 8, 9, 10}
// Initialize a variable to hold the sum of even numbers
var sum int
// Iterate through the slice
// Check if the number is even
// If it is, add it to the sum
// Print the sum to the screen
fmt.Println("Sum of even numbers:", sum)
}All lessons in Slices and Maps in Golang
1Introduction
Introduction2Slices
Slices vs ArraysAdd Element to SliceSlicingSlicing WaysReslicingSlice CapacityMax CapacityIterate Over a SliceRecap Challenge #1