Use if, else if, and else when code has several possible paths.

else if `else if` checks another condition only when the earlier `if` condition was false.

If Else

score
if_else.go
Replay: real traced execution (multi-file project)
package main

import "fmt"

func main() {
	var score = 82
	grade := ""

	if score >= 90 {
		grade = "A"
	} else if score >= 75 {
		grade = "B"
	} else {
		grade = "C"
	}

	fmt.Println("score=", score)
	fmt.Println("grade=", grade)
}
package main

import "fmt"

func main() {
	var score = 61
	grade := ""

	if score >= 90 {
		grade = "A"
	} else if score >= 75 {
		grade = "B"
	} else {
		grade = "C"
	}

	fmt.Println("score=", score)
	fmt.Println("grade=", grade)
}
package main

import "fmt"

func main() {
	var score = 95
	grade := ""

	if score >= 90 {
		grade = "A"
	} else if score >= 75 {
		grade = "B"
	} else {
		grade = "C"
	}

	fmt.Println("score=", score)
	fmt.Println("grade=", grade)
}
  1. score ← 82, grade ← ""

    5func main() {6  var score→ 82 = 82 //@score=95, 617  grade→ "" := ""
  2. grade ← "B"

    10  grade = "A"11} else if score82 >= 75 {12  grade→ "B" = "B"13} else {
  3. fmt.Println("score=", score)

    17  fmt.Println("score=", score82)18  fmt.Println("grade=", grade"B")19}
    outputscore= 82
    grade= B
  1. score ← 61, grade ← ""

    5func main() {6  var score→ 61 = 617  grade→ "" := ""
  2. grade ← "C"

    12  grade = "B"13} else {14  grade→ "C" = "C"15}
  3. fmt.Println("score=", score)

    17  fmt.Println("score=", score61)18  fmt.Println("grade=", grade"C")19}
    outputscore= 61
    grade= C
  1. score ← 95, grade ← ""

    5func main() {6  var score→ 95 = 957  grade→ "" := ""
  2. grade ← "A"

    9if score95 >= 90 {10  grade→ "A" = "A"11} else if score >= 75 {
  3. fmt.Println("score=", score)

    17  fmt.Println("score=", score95)18  fmt.Println("grade=", grade"A")19}
    outputscore= 95
    grade= A

Follow the Branch

  1. score starts at 82.
  2. The >= 90 check is false, so grade A is skipped.
  3. The >= 75 check is true.
  4. grade becomes B, so the program prints score= 82 and grade= B. | score | branch taken | grade | | --- | --- | --- | | 82 | score >= 75 | B | | 95 | score >= 90 | A | | 61 | else | C |

Exercise: if_else.go

Reproduce the default grade B, then use the pinned score variants to predict why 95 gives A and 61 gives C.