In this tutorial you will learn about the Go For Range and its application with practical example.
Go For Range
In GoLang, for loop with a “range” clause iterates through every element in an array, slice, string, map, or values received on a channel. A range
keyword is used to iterate over slices, arrays, strings, maps or channels.
Synatx:-
1 2 3 |
for key, value := range collection { //block of statements } |
here, individual keys and values are held in the corresponding variable and key or value can be omitted if one or the other is not needed using ‘_’
Example:-
1 2 3 4 5 6 7 8 9 10 11 |
package main import "fmt" func main() { langs := []string{"Go", "C", "C++", "Java"} fmt.Println("W3Adda - Go For Each Loop.") for i,s := range langs{ fmt.Println(i, s) } } |
Output:-
Go For Range with Strings
For a string, the for loop iterates over each characters’s Unicode code points. The first value is the starting byte index of the rune
and the second the rune
itself.
Example:-
1 2 3 4 5 6 7 8 9 10 |
package main import "fmt" func main() { fmt.Println("W3Adda - Go For Each with Strings") for i,s := range "W3Adda"{ fmt.Printf("%U represents %c and it is at position %d\n", s, s, i) } } |
Output:-
Go For Range with Map
In GoLang, range
on map iterates over key/value pairs. It can also iterate over just the keys of a map.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package main import "fmt" func main() { fmt.Println("W3Adda - Go For Each with Map") fruits := map[string]string{"A": "Apple", "B": "banana", "C": "Cherry"} for key, value := range fruits { fmt.Printf("%s -> %s\n", key, value) } for key := range fruits { fmt.Println("key:", key) } } |
Output:-
Go For Range with Channel
For channel, it iterates over values sent on the channel until closed.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package main import "fmt" func main() { fmt.Println("W3Adda - Go For Each with Channel") ch := make(chan string) go func() { ch <- "W" ch <- "3" ch <- "A" ch <- "D" ch <- "D" ch <- "A" close(ch) }() for n := range ch { fmt.Println(n) } } |
Output:-