Lesson 6 of 38 · Fundamentals
Go if/else and switch Statements
Programs make decisions all the time: is the hero still standing, did the player pick the right door, which reward does a score earn? In Go you make decisions with if and switch.
Both are simpler and stricter than in many languages: no parentheses around conditions, mandatory braces, and no accidental fall-through from one case into the next.
if, else if and else
package main
import "fmt"
func main() {
hp := 35
if hp <= 0 {
fmt.Println("defeated")
} else if hp < 50 {
fmt.Println("wounded")
} else {
fmt.Println("healthy")
}
}
wounded
Go checks the conditions from top to bottom and runs the block of the first one that is true; else runs when none is. There are no parentheses around a condition, but the braces are required — even for a one-line body. The condition must be a real bool: if hp { is a compile error (non-boolean condition in if statement), because Go has no "truthy" numbers or strings.
Comparison and logical operators
Comparison operators produce a bool: == (equal), != (not equal), <, <=, > and >=. They work on numbers and on strings, which are compared byte by byte. Combine conditions with the logical operators:
a && b— and: true when both sides are true.a || b— or: true when at least one side is true.!a— not: true whenais false.
level := 12
hasKey := true
if level >= 10 && hasKey {
fmt.Println("The gate opens")
}
if !hasKey || level < 5 {
fmt.Println("Come back later")
}
&& and || short-circuit: when the left side already decides the result, the right side is never evaluated. && binds tighter than ||, so use parentheses when you mix them and the order isn't obvious.
if with a short statement
An if can start with a short statement, separated from the condition by a semicolon. A variable declared there exists only inside the if and its else branches:
if left := 100 - 35; left > 50 {
fmt.Println("more than half left:", left)
} else {
fmt.Println("only", left, "left")
}
// left is undefined here
This keeps helper variables out of the surrounding code. You will use the pattern constantly for error handling: if err := save(); err != nil { ... }.
switch
A switch compares one value against a list of cases — much tidier than a long else if chain:
package main
import "fmt"
func main() {
day := "Sun"
switch day {
case "Sat", "Sun":
fmt.Println("weekend")
case "Mon", "Tue", "Wed", "Thu", "Fri":
fmt.Println("weekday")
default:
fmt.Println("unknown day")
}
}
weekend
A case may list several values separated by commas. The optional default runs when no case matches. Most importantly, every case ends on its own: unlike C, Java or JavaScript, Go never falls through into the next case automatically, so there is no break to forget.
switch without a condition
Leave out the value, and each case becomes a condition of its own. Go picks the first case that is true:
score := 83
switch {
case score >= 90:
fmt.Println("excellent")
case score >= 80:
fmt.Println("good")
default:
fmt.Println("keep practising")
}
This prints good. A bare switch is short for switch true and is the idiomatic way to write a long if/else if chain.
fallthrough
If you really want a case to continue into the next one, end it with fallthrough. It runs the next case's body without checking its condition. Most Go code never needs it:
switch level := 2; level {
case 2:
fmt.Println("bonus item")
fallthrough
case 1:
fmt.Println("gold")
}
// prints "bonus item", then "gold"
As the example shows, a switch can start with a short statement, just like if.
Common mistakes
elseon a new line:}andelsemust share a line, or you getsyntax error: unexpected keyword else.=instead of==:if x = 5is a compile error (cannot use assignment x = 5 as value), not a silent bug as in C.- Wrong case order in a bare
switch: ifscore >= 60comes beforescore >= 90, every good score stops at the first case. Put the most specific condition first. - Writing
breakat the end of every case: harmless, but unnecessary in Go.
Assignment
The function skeletons are given — put your code where the TODO comments are and use return to hand back the result.
Grade(score int) stringreturns the letter grade for a score from 0 to 100:"A"for 90–100,"B"for 80–89,"C"for 70–79,"D"for 60–69 and"F"below 60. Scores below 0 or above 100 return"invalid".DayType(day string) stringreturns"weekend"for"Saturday"and"Sunday","weekday"for"Monday"through"Friday", and"unknown"for anything else. Use aswitchwith several values per case.IsLeapYear(year int) boolreports whetheryearis a leap year: years divisible by 4 are leap years, except those divisible by 100 — unless they are also divisible by 400. So 2024 and 2000 are leap years, but 2023 and 1900 are not.
If/else and conditions in other languages
- JavaScript if/else Statements and Comparison Operators · JavaScript
- Python If, Elif and Else Statements · Python
- Java if/else and switch Statements · Java
- C# if/else, switch and Switch Expressions · C#
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .