Go - slice iteration example

In this example, we will show you how to iterate over a slice in Go with an example.

With for loops, we can iterate over slice elements in Go.

Go - slice iteration example

In the example, we iterate over a slice of days with for/range statements.


package main

import "fmt"

func main() {

    days := []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

    for idx, day := range days {

        fmt.Println(idx, day)
    }
}

Output:

0 Monday
1 Tuesday
2 Wednesday
3 Thursday
4 Friday
5 Saturday
6 Sunday

In the following example, we iterate a slice with a classic for loop.


package main

import "fmt"

func main() {

    days := []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

    for i := 0; i < len(days); i++ {

        fmt.Println(days[i])
    }
}

Output:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Comments