Decisions: if, else and switch
A useful program makes decisions: whether the user is an adult, whether the file exists, whether the balance is enough. Go offers two tools for this: if with its variants and switch. Both are simpler than in many other languages, because Go removed several classic sources of errors: there are no parentheses around the condition, braces are mandatory and the condition must be a real bool, not a number or a text.
if, else if and else
The syntax is if condition { ... } else if other { ... } else { ... }. The else must be on the same line as the previous closing brace. A feature widely used in Go is the initialization statement: you can declare a variable right before the condition, separated by a semicolon, and that variable only exists inside the if and its else branches. This keeps the scope small and is the usual pattern for checking errors, as you will see in week 3.
package main
import "fmt"
func grade(score int) string {
if score >= 90 {
return "A"
} else if score >= 70 {
return "B"
} else if score >= 50 {
return "C"
}
return "F"
}
func main() {
fmt.Println(grade(95), grade(72), grade(10))
// initialization statement: n only lives inside the if
if n := len("gopher"); n > 5 {
fmt.Println("long word", n)
} else {
fmt.Println("short word", n)
}
}switch
The switch compares an expression with several cases and runs the first one that matches. Unlike C or Java, Go does not need break: each case ends on its own and does not fall into the next. If you want that behavior, you write fallthrough explicitly, which is rare. A case can group several values separated by commas. There is also the switch without an expression, which is equivalent to a chain of if and else if with boolean conditions in each case, and usually looks cleaner. The default case runs if none matches.
package main
import "fmt"
func dayType(day string) string {
switch day {
case "saturday", "sunday":
return "weekend"
case "monday", "tuesday", "wednesday", "thursday", "friday":
return "weekday"
default:
return "unknown"
}
}
func temperature(t float64) string {
switch { // no expression: each case is a condition
case t < 0:
return "freezing"
case t < 20:
return "mild"
default:
return "hot"
}
}
func main() {
fmt.Println(dayType("sunday"), dayType("monday"), dayType("abc"))
fmt.Println(temperature(-3), temperature(15), temperature(30))
}Common mistakes
The first mistake of people coming from other languages is writing if x { } with an integer x, expecting 0 to be false; in Go that does not compile. Another mistake is putting else on a new line, which produces a syntax error because the compiler inserts an automatic semicolon at the end of the previous line. A third is forgetting that case order matters: in a switch without an expression, the first true case wins, so put the most specific conditions first.
- The if condition must be bool.
- No parentheses are used, but braces are mandatory.
- switch needs no break; use fallthrough only if you really want it.
- A case accepts several values: case 1, 2, 3.
- The variable declared in an if initializer dies when the if ends.
✎ Meine Notizen
Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen