A for loop is used to iterate over elements in a variety of data structures (e.g., a slice, an array, a map, or a string).
The for statement supports one additional form that uses the keyword range to iterate over an expression that evaluates to an array, slice, map, string, or channel.
The basic syntax for a for-range loop is:
for index, value := range mydatastructure {
fmt.Println(value)
}
index is the index of the value we are accessing.value is the actual value we have on each iteration.mydatastructure holds the data structure whose values will be accessed in the loop.Note that the above example is highly generalized. The case-by-case examples given below will help you understand the syntax further.
The for-range loop can be used to access individual characters in a string.
package mainimport "fmt"func main() {for i, ch := range "World" {fmt.Printf("%#U starts at byte position %d\n", ch, i)}}
The for-range loop can be used to access individual key-value pairs in a map.
package mainimport "fmt"func main() {m := map[string]int{"one": 1,"two": 2,"three": 3,}for key, value := range m {fmt.Println(key, value)}}
For channels, the iteration values are the successive values sent on the channel until its close.
package mainimport "fmt"func main() {mychannel := make(chan int)go func() {mychannel <- 1mychannel <- 2mychannel <- 3close(mychannel)}()for n := range mychannel {fmt.Println(n)}}
Free Resources