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.
packagemainimport"fmt"funcmain() { str :="Hello, world!"for i, c :=range str { fmt.Printf("str[%d] = %c type %T\n", i, c, c) }}
str[0] = H typeint32str[1] = e typeint32str[2] = l typeint32str[3] = l typeint32str[4] = o typeint32str[5] = , typeint32str[6] =typeint32str[7] = w typeint32str[8] = o typeint32str[9] = r typeint32str[10] = l typeint32str[11] = d typeint32str[12] =!typeint32
Contoh code looping for range pada array
packagemainimport"fmt"funcmain() { values := [7]int{1, 3, 5, 7, 9, 11, 13}for i, val :=range values { fmt.Printf("value[%d] = %d \n", i, val) }}
packagemainimport ("fmt")funcmain() { ch :=make(chanint)gofunc() {for i :=0; i <100; i++ {// channel in ch <- i }// channel must be close// if not will be deadlockclose(ch) }()// channel outfor v :=range ch { fmt.Println(v) }}