Tsallaka zuwa abun ciki
Justice Tech School

For Loops

for has three forms: the counting form, a condition only form like while, and range over slices, maps and strings. break exits and continue skips to the next round. Labels can break outer loops.

Example
for i := 0; i < 5; i++ {
	if i == 1 {
		continue
	}
	if i == 4 {
		break
	}
	fmt.Print(i, " ")
}
fmt.Println()
fruits := []string{"apple", "banana"}
for i, f := range fruits {
	fmt.Println(i, f)
}
for i := range 3 {
	fmt.Print(i, ",")
}
fmt.Println()
for _, ch := range "Go" {
	fmt.Print(string(ch), "-")
}
fmt.Println()

Result

0 2 3 
0 apple
1 banana
0,1,2,
G-o-

Exercise

Skip to the next round.

if i == 2 {  }

Quiz Test

What does range give for a slice?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.