Go: Reading a slice using range

Filipe Munhoz
2 min readAug 11, 2020

Slices are a data structures built on the top of an array that have a capacity to store a numbered (indexed) list of the same type. Unlike arrays, slices has flexible size. In this session we are going to focus on how to iterate over a slice containing elements using range.

Declaring a slice

First we will declare our new slice containing four elements.

func main() {
styles := []string{“Rock”, “Country”, “Blues”, “Jazz”}
}

Reading a slice

There are more than one way to read slices, lets see three methods.

Method 1

Reading slice using only the first value (index) returned on for.

package mainimport (
“fmt”
)
func main() {
styles := []string{“Rock”, “Country”, “Blues”, “Jazz”}
printStyles(styles)
}
func printStyles(styles []string) {
for i := range styles {
fmt.Println(“Style:”, styles[i])
}
}

In this example, "for" returned a variable called "i" that represents the index number on the list "styles". We use this index to get the corresponding value on the slice.

Method 2

Reading slice using two values returned on for.

package mainimport (
“fmt”
)
func main() {
styles := []string{“Rock”, “Country”, “Blues”, “Jazz”}
printStyles(styles)
}
func printStyles(styles []string) {
for i, style := range styles {
fmt.Printf(“Style: %v at index %v\n”, style, i)
}
}

This method returns two variables: "i" that is the index position on list and the elements "style".

We can read the element directly using the fmt.Printf passing %v value and the variable "style"

We need to read both values otherwise Go compiler will complain that is a variable that is not used.

Method 3

Reading a slice ignoring index variable "i"

package mainimport (
“fmt”
)
func main() {
styles := []string{“Rock”, “Country”, “Blues”, “Jazz”}
printStyles(styles)
}
func printStyles(styles []string) {
for _, style := range styles {
fmt.Printf(“Style: %v\n”, style)
}
}

From preventing Go compiler complaining about unsed variables, on the for syntax we change first returned variable to a underscore "_", it will be ignored and there is no need of reading the index.

Thanks for reading.

--

--