Line At A Time
Lesson 22: Continue
Continue Skip one trip around a loop with continue.
1package main
2
3import "fmt"
4
5func main() {
6 for i := 1; i <= 5; i++ {
7 if i == 3 {
8 continue
9 }
10 fmt.Println(i)
11 }
12}
Terminal
$ go run main.go
1
2
4
5
Every line, explained
package main
Every Go file starts by saying which package it belongs to. package main means "this is a program you can run", and Go will look inside it for func main.
import "fmt"
import brings in a package from Go's standard library. "fmt" (short for format) is the one full of printing tools, like fmt.Println.
func main() {
func main() { ... } is where a Go program starts. When you run the program, Go finds func main inside package main and runs everything between its braces, top to bottom.
for i := 1; i <= 5; i++ {
This counter starts at 1, and <= means "less than or equal", so the loop counts 1, 2, 3, 4, 5.
if i == 3 {
if checks a condition. Go style: NO round brackets around the condition, but the curly braces { } are always required, and the { must sit on the same line as the if. We single out the moment the counter hits 3.
continue
continue skips the REST of this trip and jumps straight to the next count. When i is 3, the Println below never happens, so 3 is missing from the output.
}
This } closes the if block.
fmt.Println(i)
fmt.Println(...) prints what is inside the brackets to the terminal, then moves to a new line (Println is short for "print line"). The capital P matters: in Go, the tools a package shares all start with a capital letter. Prints 1, 2, 4 and 5, but not 3.
}
This } closes the for loop.
}
This closing brace } ends func main.