Looping for range digunakan untuk mengulangi urutan pada value dengan tipe data string, array, slice, map dan channel.
Contoh code looping for range pada string
Looping di string di Golang menghasilkan value dengan tipe data rune bukan byte.
package main
import "fmt"
func main() {
str := "Hello, world!"
for i, c := range str {
fmt.Printf("str[%d] = %c type %T\n", i, c, c)
}
}
str[0] = H type int32
str[1] = e type int32
str[2] = l type int32
str[3] = l type int32
str[4] = o type int32
str[5] = , type int32
str[6] = type int32
str[7] = w type int32
str[8] = o type int32
str[9] = r type int32
str[10] = l type int32
str[11] = d type int32
str[12] = ! type int32
Contoh code looping for range pada array
package main
import "fmt"
func main() {
values := [7]int{1, 3, 5, 7, 9, 11, 13}
for i, val := range values {
fmt.Printf("value[%d] = %d \n", i, val)
}
}
package main
import (
"fmt"
)
func main() {
ch := make(chan int)
go func() {
for i := 0; i < 100; i++ {
// channel in
ch <- i
}
// channel must be close
// if not will be deadlock
close(ch)
}()
// channel out
for v := range ch {
fmt.Println(v)
}
}