golang for each code example

Example 1: golang loop through array

arr := []int{1, 2, 3, 4, 5}
//using range 
for index, ele := range arr { // you can escape index by _ keyword
	fmt.Println(index, ele)
}

Example 2: loop list golang

a := []string{"Foo", "Bar"}
for i, s := range a {
    fmt.Println(i, s)
}

Example 3: go iterate over slice

nums := []int{2, 3, 4}
    sum := 0
    for _, num := range nums {
        sum += num
    }
    fmt.Println("sum:", sum)

Example 4: golang range arrat

for i, num := range nums {
        if num == 3 {
            fmt.Println("index:", i)
        }
    }

Example 5: foreach golang

package main

import "fmt"

func main() {

	myList := []string{"dog", "cat", "hedgehog"}

	// for {key}, {value} := range {list}
	for _, animal := range myList {
		fmt.Println("My animal is:", animal)
	}
}

Tags:

Go Example