Foundations
If Statements
Use if and else to choose work based on a condition.
if statement
An `if` statement runs one block when its condition is true and an `else` block when it is false.
If Statements
if_intro.go
Replay: real traced execution (multi-file project)
package main
import "fmt"
func main() {
var temperature = 72
status := ""
if temperature >= 80 {
status = "warm"
} else {
status = "comfortable"
}
fmt.Println("temperature=", temperature)
fmt.Println("status=", status)
}
package main
import "fmt"
func main() {
var temperature = 55
status := ""
if temperature >= 80 {
status = "warm"
} else {
status = "comfortable"
}
fmt.Println("temperature=", temperature)
fmt.Println("status=", status)
}
package main
import "fmt"
func main() {
var temperature = 90
status := ""
if temperature >= 80 {
status = "warm"
} else {
status = "comfortable"
}
fmt.Println("temperature=", temperature)
fmt.Println("status=", status)
}
temperature ← 72, status ← ""
5func main() {6 var temperature→ 72 = 72 //@temperature=55, 907 status→ "" := ""status ← "comfortable"
10 status = "warm"11} else {12 status→ "comfortable" = "comfortable"13}fmt.Println("temperature=", temperature)
15 fmt.Println("temperature=", temperature72)16 fmt.Println("status=", status"comfortable")17}outputtemperature= 72 status= comfortable
temperature ← 55, status ← ""
5func main() {6 var temperature→ 55 = 557 status→ "" := ""status ← "comfortable"
10 status = "warm"11} else {12 status→ "comfortable" = "comfortable"13}fmt.Println("temperature=", temperature)
15 fmt.Println("temperature=", temperature55)16 fmt.Println("status=", status"comfortable")17}outputtemperature= 55 status= comfortable
temperature ← 90, status ← ""
5func main() {6 var temperature→ 90 = 907 status→ "" := ""status ← "warm"
9if temperature90 >= 80 {10 status→ "warm" = "warm"11} else {fmt.Println("temperature=", temperature)
15 fmt.Println("temperature=", temperature90)16 fmt.Println("status=", status"warm")17}outputtemperature= 90 status= warm
Follow the Branch
temperaturestarts at72.statusstarts as an empty string.- Go checks whether
temperature >= 80. 72is below80, so theelsebranch setsstatustocomfortable.- The program prints
temperature= 72andstatus= comfortable. | temperature | check | status | | --- | --- | --- | | 55 |55 >= 80is false | comfortable | | 72 |72 >= 80is false | comfortable | | 90 |90 >= 80is true | warm |
Exercise: if_intro.go
Reproduce status= comfortable for temperature 72, then try 55 and 90 and predict the branch result.