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

temperature
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)
}
  1. temperature ← 72, status ← ""

    5func main() {6  var temperature→ 72 = 72 //@temperature=55, 907  status→ "" := ""
  2. status ← "comfortable"

    10  status = "warm"11} else {12  status→ "comfortable" = "comfortable"13}
  3. fmt.Println("temperature=", temperature)

    15  fmt.Println("temperature=", temperature72)16  fmt.Println("status=", status"comfortable")17}
    outputtemperature= 72
    status= comfortable
  1. temperature ← 55, status ← ""

    5func main() {6  var temperature→ 55 = 557  status→ "" := ""
  2. status ← "comfortable"

    10  status = "warm"11} else {12  status→ "comfortable" = "comfortable"13}
  3. fmt.Println("temperature=", temperature)

    15  fmt.Println("temperature=", temperature55)16  fmt.Println("status=", status"comfortable")17}
    outputtemperature= 55
    status= comfortable
  1. temperature ← 90, status ← ""

    5func main() {6  var temperature→ 90 = 907  status→ "" := ""
  2. status ← "warm"

    9if temperature90 >= 80 {10  status→ "warm" = "warm"11} else {
  3. fmt.Println("temperature=", temperature)

    15  fmt.Println("temperature=", temperature90)16  fmt.Println("status=", status"warm")17}
    outputtemperature= 90
    status= warm

Follow the Branch

  1. temperature starts at 72.
  2. status starts as an empty string.
  3. Go checks whether temperature >= 80.
  4. 72 is below 80, so the else branch sets status to comfortable.
  5. The program prints temperature= 72 and status= comfortable. | temperature | check | status | | --- | --- | --- | | 55 | 55 >= 80 is false | comfortable | | 72 | 72 >= 80 is false | comfortable | | 90 | 90 >= 80 is true | warm |

Exercise: if_intro.go

Reproduce status= comfortable for temperature 72, then try 55 and 90 and predict the branch result.