While, Go-style
Count down to lift-off using for!
1package main
2
3import "fmt"
4
5func main() {
6 countdown := 3
7 for countdown > 0 {
8 fmt.Println(countdown)
9 countdown = countdown - 1
10 }
11 fmt.Println("Lift off!")
12}
$ go run main.go
3
2
1
Lift off!
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.
countdown := 3- := 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 countdown > 0 {- Go has exactly ONE loop keyword: for. Write it with just a condition and it behaves like other languages' while, repeating as long as the condition is true. This one repeats while countdown is greater than 0.
fmt.Println(countdown)- 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 3, then 2, then 1.
countdown = countdown - 1- Takes 1 off countdown each trip. Without this line the loop would never end!
}- This } closes the for loop.
fmt.Println("Lift off!")- 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. Outside the loop: it runs once, after the loop has finished.
}- This closing brace } ends func main.