Making Decisions

Making Decisions

Making Decisions

Your code needs to make choices. An if statement runs a block of code only when a condition is true:

example.go
if temperature > 35 {
    fmt.Println("Too hot")
}

If temperature is 40, the condition temperature > 35 is true, so the code inside the braces runs. If temperature is 20, the condition is false and the block is skipped entirely.

You can add an else block that runs when the condition is false:

example.go
if temperature > 35 {
    fmt.Println("Too hot")
} else {
    fmt.Println("Not too hot")
}

For multiple conditions, chain them with else if. Go evaluates top to bottom and runs the first block that matches:

example.go
if temperature > 35 {
    fmt.Println("Too hot")
} else if temperature > 20 {
    fmt.Println("Just right")
} else {
    fmt.Println("Too cold")
}

If temperature is 25, the first condition (> 35) is false, so Go moves to the next. The second condition (> 20) is true, so it prints "Just right" and skips the rest.

A Few Things to Notice

No parentheses around the condition (unlike most languages), and the braces {} are mandatory, even for one-liners.

else and else if must go on the same line as the closing }:

example.go
}               // ❌ syntax error
else if ... {

} else if ... { // ✅

Go auto-inserts a semicolon at the end of a line, so else on its own line ends the if before Go sees it.

Setting a Variable Inside a Branch

When a variable is declared before the if, assign to it inside the branches with =, not :=:

example.go
category := ""
if status >= 500 {
    category = "server error"   // = assigns to the category above
}

Writing category := inside the if makes a new variable that vanishes at the closing }, so the outer one stays "". Go compiles it without a warning, which is what makes it an easy trap.

>_Exercise

Exercise: Grade Calculator

Fill in the if/else if/else block inside getGrade to check the score parameter and set grade to the correct letter:

  • score 90 or above → "A"
  • score 80 or above → "B"
  • score 70 or above → "C"
  • score 60 or above → "D"
  • score below 60 → "F"
Stuck? Reveal a hint to help you.
Hints (0/5)
Key Takeaway
Next UpCombining conditions with logical operators.