Conditions, switch and case lists
Conditions are if and switch. Both take an optional initialisation statement, both scope the variables they declare to the statement, and neither needs parentheses around its condition. Go has no ternary operator, and the reason is the same one that keeps ++ a statement: an expression never has a side effect in this language.
if
The body must have braces, even for one line, and an else belongs on the line of the closing brace. The initialisation form, if n := len(s); n > 3, declares a variable that exists only inside the branches, which is the idiomatic way to check a value once and use it in both.
package main
import "fmt"
func class(score int) string {
if score < 0 || score > 100 {
return "out of range"
}
if score >= 90 {
return "A"
} else if score >= 75 {
return "B"
} else if score >= 60 {
return "C"
}
return "D"
}
func main() {
for _, score := range []int{95, 80, 61, 40, -1} {
fmt.Printf("%4d -> %s\n", score, class(score))
}
if n := len("hello"); n > 3 {
fmt.Println("length in the if scope:", n)
}
}
go run if.go
95 -> A
80 -> B
61 -> C
40 -> D
-1 -> out of range
length in the if scope: 5
A chain of else if is a linear scan, and a switch is the better shape once the conditions test the same value. The early return for the out-of-range case keeps the rest of the function flat, which Go code prefers to deep nesting.
switch with a value
A Go switch does not fall through: the first matching case ends the statement. Several values share a case, separated by commas, and the cases need not be constants. That removes the break that C requires at the end of every branch and the bug of forgetting it.
package main
import (
"fmt"
"time"
)
func season(month time.Month) string {
switch month {
case time.December, time.January, time.February:
return "winter"
case time.March, time.April, time.May:
return "spring"
case time.June, time.July, time.August:
return "summer"
case time.September, time.October, time.November:
return "autumn"
}
return "unknown"
}
func main() {
for _, m := range []time.Month{time.January, time.April, time.July, time.October} {
fmt.Println(m, season(m))
}
}
go run switch.go
January winter
April spring
July summer
October autumn
The cases are compared in order, and default runs when none matches. A switch with no expression, below, is the chain of conditions written as a table.
switch without a value, and fallthrough
switch { case n < 0: ... } evaluates each case as a boolean, which reads better than a long else if chain. fallthrough is the explicit way to continue into the next case; it is rare, it must be the last statement of a branch, and it does not test the next case.
package main
import "fmt"
func describe(n int) string {
switch {
case n < 0:
return "negative"
case n == 0:
return "zero"
case n%2 == 0:
return "positive and even"
default:
return "positive and odd"
}
}
func demo(n int) {
switch n {
case 1:
fmt.Println("one")
fallthrough
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
}
func main() {
for _, n := range []int{-2, 0, 4, 7} {
fmt.Println(n, describe(n))
}
demo(1)
demo(2)
demo(3)
}
go run tagless.go
-2 negative
0 zero
4 positive and even
7 positive and odd
one
two
two
three
The last three calls show the difference: demo(1) prints one and two, fallthrough(2) prints two only, and fallthrough(3) prints three. The type switch of the interfaces part is the same syntax with a type instead of a value.
The classic mistake
A C programmer writes = where == belongs. Go makes assignment a statement, so the parser refuses it inside a condition instead of accepting it as a value of one.
package main
import "fmt"
func main() {
x := 1
if x = 2 {
fmt.Println("two")
}
}
go build assignment.go
# command-line-arguments
./assignment.go:7:7: syntax error: cannot use assignment x = 2 as value
Exercises
- Rewrite the class function with a single switch and no else. Which version is easier to extend with a new grade?
- Add a case to the season switch for an invalid month value. Which cases can the compiler still not check?
- Print a number in words from zero to nine with a tagless switch, then with a slice of strings. Which one would you keep?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What must the body of an if statement have?
Answer
Braces
Go requires braces even for a single statement, which keeps the shape of the code stable.
-
Where does the variable of
if n := f(); n > 0exist?Answer
Only inside the if and its branches
The initialisation statement scopes its variables to the if statement, else branches included.
-
Does a Go switch case fall through by default?
Answer
No, it ends at the case
Each case ends the switch unless fallthrough is written explicitly.
-
What does
switch { case n < 0: }switch on?Answer
The boolean value of each case
A switch with no expression is the idiomatic chain of conditions.
-
What does this program print?
package main import "fmt" func main() { x := 5 if x > 3 { fmt.Println("big") } else { fmt.Println("small") } }Answer
big
Only the branch whose condition holds runs.
-
What does this program print?
package main import "fmt" func main() { switch 2 { case 1: fmt.Println("one") case 2: fmt.Println("two") fallthrough case 3: fmt.Println("three") } }Answer
two / three
fallthrough continues into the next case without testing it.
-
What does this program print?
package main import "fmt" func main() { switch 5 { case 1, 2: fmt.Println("small") case 5, 6: fmt.Println("middle") default: fmt.Println("other") } }Answer
middle
A case may list several values, and the first matching case ends the switch.
-
What does the compiler say about
if x = 2 { }?Answer
cannot use assignment x = 2 as value
Assignment is a statement in Go, so it cannot stand where a boolean is expected.
-
What is the advantage of a tagless switch over else if?
Answer
It states one shape per case in a readable table
Go does not check exhaustiveness; the gain is readability and a single indentation level.
-
Can a switch case compare strings?
Answer
Yes, any comparable value
Cases may be any expression of the switched type, including non-constant strings.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev