Coding for All
Lesson 11: The OR Operator
The OR Operator Combine conditions with ||.
1package main
2
3import "fmt"
4
5func main() {
6 likesCats := true
7 likesDogs := false
8 if likesCats || likesDogs {
9 fmt.Println("You like animals!")
10 }
11}
Terminal
$ go run main.go
You like animals!
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.
likesCats := 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.)
likesDogs := 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 likesCats || likesDogs {
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 OR: the whole condition is true if at least one side is true, and true || false is true.
fmt.Println("You like animals!")
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 } closes the if block.
}
This closing brace } ends func main.