In this section, we're going to learn how to iterate over an array. Iterating over an array is one of the most fundamental and common operations in Go programming. Let's go to our editor and see how we can do it easily:
package main import "fmt" func main(){ numbers := []int{1, 5, 3, 6, 2, 10, 8} for index,value := range numbers{ fmt.Printf("Index: %v and Value: %v\n", index, value) } }
We obtain the following output from the preceding code:
That's how easily you can iterate over various types of slice, including string slices, byte slices, or byte arrays.
Sometimes, you won't need the index
. In that case, you can just ignore it by using underscore (_
). This will mean that you're only interested in the value. To carry this out, you can type in the following code:
package main import "fmt" func main(){ numbers := []int{1, 5, 3, 6, 2, 10, 8} for _,value := range numbers{ // fmt.Printf("Index: %v and Value: %v\n", index, value) fmt.Println(value...