Conditionals
Prerequisites: Reading user input
Syntax
if condition {
// ...
} else if otherCondition {
// ...
} else {
// ...
}
- No parentheses around the condition.
- Braces are always required, even for a single line.
elsemust be on the same line as the closing}.
An if can also start with a short init statement, separated
from the condition by ;. Variables declared there only exist
inside the if/else blocks:
if n, err := strconv.Atoi(input); err != nil {
fmt.Println("not a number")
} else {
fmt.Println("you typed", n)
}
// n and err don't exist here
Example
package main
import (
"fmt"
"strconv"
)
func main() {
temperature := 28
if temperature > 30 {
fmt.Println("Hot")
} else if temperature > 20 {
fmt.Println("Warm")
} else {
fmt.Println("Cold")
}
if n, err := strconv.Atoi("42"); err == nil {
fmt.Println("Parsed:", n)
}
loggedIn := true
isAdmin := false
if loggedIn && !isAdmin {
fmt.Println("Regular user")
}
}
Expected output
Warm
Parsed: 42
Regular user
Common mistakes
- Using a non-boolean as a condition. Go has no "truthy" values,
so
if count { ... }fails withnon-boolean condition in if statement— writeif count != 0. - Putting
elseon a new line after}— a syntax error because of automatic semicolon insertion. - Trying to use a variable from an
ifinit statement after theifhas ended.
Practice
Given score := 73, print Pass if the score is 50 or more and
Fail otherwise. Then, using an init statement, parse the string
"19" and print Adult if it's 18 or more.
Show solution
package main
import (
"fmt"
"strconv"
)
func main() {
score := 73
if score >= 50 {
fmt.Println("Pass")
} else {
fmt.Println("Fail")
}
if age, err := strconv.Atoi("19"); err == nil && age >= 18 {
fmt.Println("Adult")
}
}