Go Break and Continue
The break statement ends a loop at once. The continue statement skips the rest of the current run.
Stop with break
The loop counts up from 0. Break ends the loop when i reaches 3.
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
if i == 3 {
break
}
fmt.Println(i)
}
}Skip one run with continue
Continue skips the print when i is 3. The loop still runs to the end.
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
if i == 3 {
continue
}
fmt.Println(i)
}
}Find the first match
The loop searches upward from 20. Break stops the search at the first multiple of 7.
package main
import "fmt"
func main() {
for i := 20; i <= 100; i++ {
if i%7 == 0 {
fmt.Println(i)
break
}
}
}Example
package main
import "fmt"
func main() {
for i := 1; i < 20; i++ {
if i == 8 {
break
}
if i == 4 {
continue
}
fmt.Println(i)
}
}Key points
- Use break to end a loop at once.
- Use continue to skip the rest of the current run.
- Break leaves the loop for good.
- Continue keeps the loop running with its next value.
In this example, the loop starts at 1 and counts upward. Continue skips the print when i is 4. Break ends the loop when i reaches 8. The printed numbers run from 1 to 7 with 4 missing.
Note
Break ends only the innermost loop around it.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
What does continue do inside a loop?