Looping

Go has a single loop statement: for

Standard for statement


for i:= 0; i < 5; i++ {
	fmt.Println(i)
}
0
1
2
3
4

Condition only (while loop)


i := 1
for i < 100 {
	fmt.Println(i)
	i = i * 2
}
1
2
4
8
16
32
64

Infinite Loop


x := 0
for {
	x++
	fmt.Println(x)
	if x == 5 {
		break
	}
}
1
2
3
4
5

Looping on

A for loop of a string converts UTF-8 to 32bit, so non standard characters are still treated as one


m := "moon๐ŸŒœy"
for i, v := range m {
	fmt.Printf("%v %8v %-6v\n", i, v, string(v))
}
0      109 m     
1      111 o     
2      111 o     
3      110 n     
4   127772 ๐ŸŒœ     
8      121 y

Countinue to label


	samples := []string{"hello", "apple_ฯ€!"}
outer:
	for _, sample := range samples {
		for i, r := range sample {
			fmt.Println(i, r, string(r))
			if r == 'l' {
				continue outer
			}
		}
		fmt.Println("Outer")
	}
0 104 h
1 101 e
2 108 l
0 97 a
1 112 p
2 112 p
3 108 l

Goto


func gotoer() {
	goto done
	for {
			fmt.Println("Skip the infinite loop")
	}
done:
	fmt.Println("Done")
}


gotoer()
Done

Notes

  • The value returned in a for-range loop is a copy, not a reference