How to loop through a slice or an array in Go or Golang?

Published October 5, 2022

To loop through a slice or an array in Go or Golang, you can use the for keyword followed by the range operator clause.

TL;DR

package main

import "fmt"

func main(){
    // slice of names
    names := []string{"John Doe", "Lily Roy", "Roy Daniels"}

    // loop through every item in the `names`
    // slice using the `for` keyword
    // and the `range` operator clause
    for indx, name := range names {
        // log the index and the value
        // of the item in the slice
        fmt.Println(indx, name)
    }
}

The range operator returns 2 values where the first value is the index of the item in the slice and the second value is the copy of the item in the slice.

For example, let's say we have a slice of names like this,

package main

func main(){
    // slice of names
    names := []string{"John Doe", "Lily Roy", "Roy Daniels"}
}

To loop through the names slice, we can write the for loop followed by the range operator clause.

Since the range operator returns 2 values where the first value is the index of the item and the second value is the copy of the item in the slice, we can use 2 variables to receive the values from the range operator after the for keyword.

It can be done like this,

package main

func main(){
    // slice of names
    names := []string{"John Doe", "Lily Roy", "Roy Daniels"}

    // loop through every item in the `names`
    // slice using the `for` keyword
    // and the `range` operator clause
    for indx, name := range names {
        // cool code here
    }
}

Now we have the index of the item and the value itself that we can use in each iteration.

For simplicity, let's log the index and the value to the console using the Prinln() method from the fmt package like this,

package main

import "fmt"

func main(){
    // slice of names
    names := []string{"John Doe", "Lily Roy", "Roy Daniels"}

    // loop through every item in the `names`
    // slice using the `for` keyword
    // and the `range` operator clause
    for indx, name := range names {
        // log the index and the value
        // of the item in the slice
        fmt.Println(indx, name)
    }
}

The output will look like this,

0 John Doe
1 Lily Roy
2 Roy Daniels

That's all. We have successfully looped through every item in the slice in Go.

See the above code live in The Go Playground.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter