Break
Escape from a loop with break.
1package main
2
3import "fmt"
4
5func main() {
6 count := 0
7 for {
8 fmt.Println(count)
9 count++
10 if count == 5 {
11 break
12 }
13 }
14}
$ go run main.go
0
1
2
3
4
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.
count := 0- := is Go's declare-and-assign: it creates a new variable AND stores a value in one step, and Go works out the type by itself. You will use := constantly in Go. (No semicolon needed; Go adds them for you behind the scenes.)
for {- for with nothing after it at all is Go's forever-loop: it would repeat until the end of time. We will need break to escape!
fmt.Println(count)- 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.
count++- count++ adds 1 to count, a short way of writing count = count + 1.
if count == 5 {- 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. Once the counter reaches 5, it is time to stop.
break- break immediately stops the loop it is inside; Go jumps to the first line after the loop's closing brace.
}- This } closes the if block.
}- This } closes the for loop.
}- This closing brace } ends func main.