Range in Go-Lang With example!
Range is a built-in function in Go that can be used to iterate over an array, slice, map, string, or channel. It simplifies the process of looping through collections and makes code more concise and readable.
Range with Arrays and Slices
To iterate over an array or slice, we can use the range
keyword followed by the array or slice variable. The range
keyword returns two values: the index of the current element and the value of the current element.
arr := []int{1, 2, 3, 4, 5}
for i, v := range arr {
fmt.Printf("index: %d, value: %d\n", i, v)
}
Output:
index: 0, value: 1
index: 1, value: 2
index: 2, value: 3
index: 3, value: 4
index: 4, value: 5
We can also omit the index or value by using the _
character:
arr := []int{1, 2, 3, 4, 5}
for _, v := range arr {
fmt.Printf("value: %d\n", v)
}
Output:
value: 1
value: 2
value: 3
value: 4
value: 5
Range with Maps
To iterate over a map, we use the range
keyword just like with arrays and slices. However, since maps are unordered collections, the order in which elements are returned is not guaranteed.
m := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
for k, v := range m {
fmt.Printf("key: %s, value: %d\n", k, v)
}
Output:
key: a, value: 1
key: b, value: 2
key: c, value: 3
Range with Strings
To iterate over a string, we use the range
keyword just like with arrays and slices. However, the value returned by range
is not a character, but the Unicode code point of the character.
s := "hello"
for _, c := range s {
fmt.Printf("%c\n", c)
}
Output:
h
e
l
l
o
Range with Channels
To iterate over a channel, we use the range
keyword just like with other collections. However, the loop will continue until the channel is closed, so it is important to close the channel once all the values have been sent.
c := make(chan int)
go func() {
defer close(c)
for i := 0; i < 5; i++ {
c <- i
}
}()
for v := range c {
fmt.Println(v)
}
Output:
0
1
2
3
4
Conclusion
Range is a powerful and flexible tool for iterating over collections in Go. It simplifies the process of looping through arrays, slices, maps, strings, and channels, and makes code more concise and readable. By mastering the range
keyword, Go developers can write more efficient and elegant code.
I hope this helps, you!!
More such articles:
https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA
\==========================**=========================
If this article adds any value to you then please clap and comment.
Letβs connect on Stackoverflow, LinkedIn, & Twitter.