Else If
Check several conditions, one after another.
1package main
2
3import "fmt"
4
5func main() {
6 number := 2
7 if number == 1 {
8 fmt.Println("one")
9 } else if number == 2 {
10 fmt.Println("two")
11 } else {
12 fmt.Println("something else")
13 }
14}
$ go run main.go
two
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.
number := 2- := 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.)
if number == 1 {- 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. == asks "are these equal?". Careful: a single = stores a value, a double == compares. 2 == 1 is false, so this block is skipped.
fmt.Println("one")- 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. Skipped: number is not 1.
} else if number == 2 {- } else if ... { adds another check that is only tried when the one above was false. Go tests each condition top to bottom and runs the first block whose condition is true. 2 == 2 is true, so this block runs.
fmt.Println("two")- 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. This line runs.
} else {- } else { must be written exactly like this in Go: closing brace, else, and opening brace all on ONE line. Go is famously strict about layout: a tool called gofmt keeps every Go program in the world formatted the same way. Only runs when every check above it failed.
fmt.Println("something else")- 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. Skipped: the else if above already matched.
}- This } closes the else block.
}- This closing brace } ends func main.