Line At A Time
Lesson 12: The AND Operator
The AND Operator Combine conditions with &&.
1package main
2
3import "fmt"
4
5func main() {
6 hungry := true
7 haveSnacks := false
8 if hungry && haveSnacks {
9 fmt.Println("Snack time!")
10 } else {
11 fmt.Println("No snacks right now")
12 }
13}
Terminal
$ go run main.go
No snacks right now
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.
hungry := true
:= 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.)
haveSnacks := false
:= 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 hungry && haveSnacks {
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. && means AND: the condition is only true if BOTH sides are true. true && false is false, so this block is skipped.
fmt.Println("Snack time!")
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: we have no snacks.
} 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.
fmt.Println("No snacks right now")
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 is the line that runs.
}
This } closes the else block.
}
This closing brace } ends func main.