If Statements
So far, your programs ran every line from top to bottom. Real programs often need to choose. Print "Pass" only when the score is high enough. Charge shipping only when the order is small. The if statement makes this choice.
An if has a condition, which is a question with a yes or no answer. The code inside the braces runs only when the answer is true:
package main
import "fmt"
func main() {
score := 72
if score >= 50 {
fmt.Println("Pass")
}
fmt.Println("Done")
}
Output:
Pass
Done
72 >= 50 is true, so Pass is printed. Done is outside the braces, so it is printed in every case. Change score to 30, and only Done appears.
Go does not need parentheses around the condition. The braces { } are always required, even when there is only one line inside them.
You met these comparison operators in the Operators lesson. Each one gives a bool, either true or false:
| Operator | Means |
|---|---|
== | equal to |
!= | not equal to |
< and > | less than, greater than |
<= and >= | less or equal, greater or equal |
Remember that == compares, and a single = puts a value into a variable.
else and else if
Add else for the code that should run when the condition is false. To test more cases, add else if. Go checks the conditions from top to bottom and runs only the first block whose condition is true:
score := 81
if score >= 90 {
fmt.Println("Grade A")
} else if score >= 75 {
fmt.Println("Grade B")
} else {
fmt.Println("Grade C")
}
Output:
Grade B
81 is not 90 or more, so the first block is skipped. 81 is 75 or more, so Grade B is printed, and Go skips the rest. The order matters here. If the score >= 75 test came first, a score of 95 would get Grade B.
else must be on the same line as the closing } of the block before it. Putting it on its own line is a compile error:
package main
import "fmt"
func main() {
score := 70
if score >= 50 {
fmt.Println("Pass")
}
else {
fmt.Println("Fail")
}
}
Output:
# command-line-arguments
./main.go:10:2: syntax error: unexpected else, expected }
The condition must be a bool
Some languages treat 0 as false and other numbers as true. Go does not. The condition must be a bool, so you write the comparison you mean:
package main
import "fmt"
func main() {
items := 3
if items {
fmt.Println("Cart is not empty")
}
}
Output:
# command-line-arguments
./main.go:7:5: non-boolean condition in if statement
The fix is if items > 0 {.
A short statement before the condition
An if can start with a short statement, followed by a semicolon. It is often used to compute a value that only the if needs:
price := 8
if total := price * 3; total > 20 {
fmt.Println("Big order:", total)
} else {
fmt.Println("Small order:", total)
}
Output:
Big order: 24
total exists only inside this if and its else blocks. Using it after the closing brace gives the error undefined: total. This keeps a helper value close to the one place that uses it.
In the exercise, finish an if, else if, else chain that picks a label for a parcel by its weight.