The till at Bimo's Meatball Stall has promo rules: spend $50 or more and get a free iced tea, $30 or more and get free crackers, below that no bonus yet. The cashier reads the rules from the top. As soon as one rule fits, the bonus is given and the rules below are not read any more.
In Go, rules like these are written with if: its block runs only when its condition is true. else if and else add other branches.
if, else if, else
package main
import "fmt"
func main() {
total := 45
if total >= 50 {
fmt.Println("Free iced tea")
} else if total >= 30 {
fmt.Println("Free crackers")
} else {
fmt.Println("No bonus yet")
}
}
$ go run stall.go
Free crackers
total |
>= 50 |
>= 30 |
Printed |
|---|---|---|---|
| 60 | true | (not checked) | Free iced tea |
| 45 | false | true | Free crackers |
| 20 | false | false | No bonus yet |
- The condition is written without brackets:
if total >= 50 {. Go accepts brackets, butgofmt(Go's built-in code formatter) removes them straight away, so nobody writes them. - Curly braces are required, even when the block is one line.
{must be on the same line asif. else ifandelsego on the same line as the}that closes the block before.- The
elseat the end is optional. Withoutelse, a total of 20 prints nothing.
The order of the conditions matters
Guess first: if the order is swapped, total >= 30 first and then total >= 50, does a customer who spends $60 get the iced tea or the crackers?
Go checks from top to bottom and stops at the first condition that is true. If the order is swapped, total >= 30 is already true for 60, so what prints is Free crackers, and the iced tea branch can never be used. Tiered rules are written from the strictest: the biggest number first.
If else is removed and it becomes two separate if statements, both are checked. A total of 60 then prints Free iced tea and Free crackers. One if/else if chain only runs one branch.
In the exercise, this chain is used inside a function, a named block of code that can be called many times:
func bonus(total int) string {
if total >= 50 {
return "Free iced tea"
} else if total >= 30 {
return "Free crackers"
}
return "No bonus yet"
}
func bonus(total int) stringmeans the functionbonustakes atotalof typeintand returns astring.returnsends a value back to the caller and leaves the function straight away. The lines after it don't run.fmt.Println(bonus(60))printsFree iced tea. The details of functions come in the functions lesson later.
The condition must be a bool
In JavaScript, if (stock) runs for any number other than 0. Go has no truthy and falsy: the condition must be a bool.
if stock {withstock := 3fails withnon-boolean condition in if statement. Writeif stock > 0 {.if total = 50 {(one=) fails withsyntax error: cannot use assignment total = 50 as value. Comparing takes==.- Several conditions are joined with
&&and||:if total >= 50 && paid {.
if with a short statement
An if may start with one short statement, separated from the condition by a semicolon:
total := 45
payment := 100
if change := payment - total; change > 0 {
fmt.Println("Change:", change)
} else {
fmt.Println("Exact amount")
}
Change: 55
change := payment - totalruns first, thenchange > 0is checked.changeonly exists inside thatifandelseblock. Using it after}fails withundefined: change. The temporary variable doesn't leak out.- You will see this pattern a lot in the errors lesson:
if err := save(); err != nil {.
No ternary
Go has no condition ? a : b operator. bonus := total >= 50 ? "iced tea" : "crackers" is refused with invalid character U+003F '?'. Write it with if:
bonus := "crackers"
if total >= 50 {
bonus = "iced tea"
}
⚠️ The wrong line and the wrong order
elseon a new line.}withelse {on the next line fails withsyntax error: unexpected keyword else, expected }. Write} else {on one line.{on a new line.if total >= 50with{below it fails withsyntax error: unexpected newline, expected { after if clause.- The order swapped. A loose condition at the top swallows the strict one below it.
- Separate
ifstatements when you meant one branch. Withoutelse, several branches can run at once.
TL;DR: if condition { ... } else if condition { ... } else { ... }: no brackets around the condition, curly braces required, { and else on the same line as }. Go checks from the top and runs only the first branch that is true, so write tiered rules from the strictest. The condition must be a bool: there is no truthy/falsy, write stock > 0. if x := ...; condition { runs a short statement first, and x only exists inside that if/else block. There is no ternary ? :, use if. Inside a function, return sends the result and leaves straight away.
⚡ One chain, one branch
Write:
total := 45
if total >= 50 {
fmt.Println("Free iced tea")
} else if total >= 30 {
fmt.Println("Free crackers")
} else {
fmt.Println("No bonus yet")
}
Meaning: The condition has no brackets, the curly braces are required, and { and else sit on the same line as }. That is the form gofmt produces. What prints here is Free crackers.
⚡ The order of the conditions
Guess first: the order is swapped, total >= 30 first, then total >= 50. What does a customer who spends 60 get?
The crackers. Go stops at the first condition that is true, and 60 >= 30 is already true. The iced tea branch is never used.
Meaning: Tiered rules are written from the strictest, the biggest number first.
⚡ The condition must be a bool
Write:
if stock > 0 {
Meaning: Go has no truthy and falsy. if stock { with stock := 3 is refused with non-boolean condition in if statement.
⚡ if with a short statement
Write:
if change := payment - total; change > 0 {
fmt.Println("Change:", change)
}
Meaning: The statement before ; runs first, then the condition is checked. change only exists inside that if and else block.