Conditionals in Go
By Flavio Copes
Learn how to use conditionals in Go, from the if, else, and else if statements to the switch statement, which needs no break after each case.
We use the if statement to execute different instructions depending on a condition:
if age < 18 {
fmt.Println("underage")
}
Notice we don’t wrap the condition in parentheses like in C or JavaScript. And the braces are always required, even for a single statement. gofmt enforces this style, so all Go code looks the same.
The else part is optional:
if age < 18 {
fmt.Println("underage")
} else {
fmt.Println("adult")
}
and can be combined with other if:
if age < 12 {
fmt.Println("child")
} else if age < 18 {
fmt.Println("teen")
} else {
fmt.Println("adult")
}
If you define any variable inside the if, that’s only visible inside the if (same applies to else and anywhere you open a new block with {}).
The if with an initial statement
Go lets you run a short statement before the condition, separated by a semicolon. The variable it declares is scoped to the if and its else:
if err := saveUser(user); err != nil {
fmt.Println(err)
}
You’ll see this pattern everywhere in Go, because functions commonly return an error as their last value and you check it right away.
When to use switch
If you’re going to have many different if statements to check a single value, it’s probably better to use switch:
switch age {
case 16:
fmt.Println("Sweet sixteen")
case 18:
fmt.Println("Just became an adult")
default:
fmt.Println(age, "years old")
}
Compared to C, JavaScript and other languages you don’t need to have a break after each case. Go stops after the first match. If you want execution to continue into the next case, you add the fallthrough keyword explicitly, but that’s rare.
A switch also works without an expression. Each case becomes a boolean condition, which reads better than a long if/else if chain:
switch {
case age < 12:
fmt.Println("child")
case age < 18:
fmt.Println("teen")
default:
fmt.Println("adult")
}
One thing that trips people up in that default case: you can’t concatenate a number and a string, so age + " years old" is a compile error with a mismatched types message. Go never converts types for you. Pass them as separate arguments to fmt.Println(), which adds a space between them, or convert first with strconv.Itoa(age).