Skip to content

Golang: How to Loop over an Array

To loop over an array in Golang, use the following snippet:

for index, value := range array {
	fmt.Println(index)
	fmt.Println(value)
}

You can throw away the index or value of these that aren’t being used as shown below:|

for _, value := range array {
	fmt.Println(value)
}

Bonus tip, for cleaner code, rather than naming the values, “value” naming them according to the data will lead to cleaner and more readable code. Especially in longer for loops.

for _, person := range people {
	fmt.Println(person)
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.