Loops in Go
For Loop
For loops in go works the same as any other programming language. To make a for loop that does 3 iterations,
for i:=0; i < 3; i++ {
fmt.Println(i)
}
// Outputs: 0,1,2
break keyword
break
keyword is used to stop the for loop from iterating further.
for i:=0; i < 4; i++ {
if i == 2 {
break
}
fmt.Println(i)
}
// Outputs: 0,1
continue keyword
continue
keyword is used to skip an iteration.
for i:=0; i < 3; i++ {
if i == 1 {
continue
}
fmt.Println(i)
}
// Outputs: 0,2
range keyword
Please refer to Arrays and Slices - How to easily loop over a slice for a detailed explanation.
Last updated on