DEV Community 👩‍💻👨‍💻

Cover image for How to loop through a slice or an array in Go or Golang?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

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

#go

Originally posted here!

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)
    }
}
Enter fullscreen mode Exit fullscreen mode

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"}
}
Enter fullscreen mode Exit fullscreen mode

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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)
    }
}
Enter fullscreen mode Exit fullscreen mode

The output will look like this,

0 John Doe
1 Lily Roy
2 Roy Daniels
Enter fullscreen mode Exit fullscreen mode

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 😃.


Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.