Golang For Loop

Arrays

When you use range with an array or a slice, it iterates over the indices and values of the elements.

package main

import "fmt"

func main() {
  	intArr := []int{11, 12, 13, 14}
  
  	for index, value := range intArr {
  		fmt.Printf("index=%d value(d)=%d value(v)=%#v\n", index, value, value)
  	}
}

-------------------------------
Output:
-------------------------------
index=0 value(d)=11 value(v)=11
index=1 value(d)=12 value(v)=12
index=2 value(d)=13 value(v)=13
index=3 value(d)=14 value(v)=14

Strings

When iterating over a string with range, it returns the index and the Unicode code point (rune – int32) of each character.

package main

import "fmt"

func main() {
	inputString := "ROBpike"
	// here value is Rune of int32
	for index, value := range inputString {
		fmt.Printf("index=%d type(T)=%T value(v)=%#v Rune(c)=%c\n", index, value, value, value)
	}

}

---------------------------------------------
Output:
---------------------------------------------
index=0 type(T)=int32 value(v)=82 Rune(c)=R
index=1 type(T)=int32 value(v)=79 Rune(c)=O
index=2 type(T)=int32 value(v)=66 Rune(c)=B
index=3 type(T)=int32 value(v)=112 Rune(c)=p
index=4 type(T)=int32 value(v)=105 Rune(c)=i
index=5 type(T)=int32 value(v)=107 Rune(c)=k
index=6 type(T)=int32 value(v)=101 Rune(c)=e

Map

When you use range with a map, it iterates over the key-value pairs.

package main

import "fmt"

func main() {
	// Key: String, Value : int
	m := map[string]int{"a": 1, "b": 2, "c": 3}

	for k, v := range m {
		fmt.Printf("Key: %s, Value: %d\n", k, v)
	}

	// Key: int, Value : String
	n := map[int]string{5: "d", 6: "e", 7: "f"}

	for k, v := range n {
		fmt.Printf("Key: %d, Value: %s\n", k, v)
	}}

---------------------------------------------
Output:
---------------------------------------------
// Key: String, Value : int
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3

// Key: int, Value : String
Key: 5, Value: d
Key: 6, Value: e
Key: 7, Value: f

Channels

When iterating over a channel with range, it retrieves values sent through the channel until the channel is closed.

package main

import "fmt"

func main() {
    ch := make(chan int, 3)
    ch <- 1
    ch <- 2
    ch <- 3
    close(ch)

    for v := range ch {
        fmt.Println(v)
    }
}

---------------------------------------------
Output:
---------------------------------------------

1
2
3

Notes

If you only need the index or key, you can ignore the value using the blank identifier _:

for i := range arr {
    fmt.Println(i)
}

If you only need the value, you can ignore the index/key similarly:

for _, v := range arr {
    fmt.Println(v)
}

The range keyword makes iterating over various data structures straightforward and readable in Go.

Leave a Reply

Your email address will not be published. Required fields are marked *