if and switch
Conditions without parentheses, a switch that does not fall through, and a short scope for a variable.
A condition in if is written without parentheses. Braces are required, even when there is a single line inside. Before the condition you can run a short assignment, and that variable lives only in the if and the else:
if err := load(); err != nil {
return err
}
Outside this if the name err does not exist. That is convenient, so you do not carry a temporary error any further. It is also easy to confuse with shadowing if the same name was already declared above: the inner := creates a new variable, it does not update the outer one.
switch by default does not fall through into the next case. You do not write break. If falling through is truly needed, you ask for it with the word fallthrough, and that is rare. Cases may be expressions, not only constants:
switch {
case n < 0:
return "minus"
case n == 0:
return "zero"
default:
return "plus"
}
An empty switch with conditions is easier to read than a long ladder of else if when there are more than three branches. switch x.(type) is a separate story about interfaces. We will reach it in its own lesson.
Boundaries
Do not hide a side effect in the condition when the branch cannot be understood without it. if user, err := repo.Find(id); err != nil is still readable. Three calls and an assignment on one line are not. Lift the preparation above, and leave in the if only what the branch depends on.
Practice
Switch fallthrough
What will the program print?
n := 1 switch n { case 1: fmt.Print("a") case 2: fmt.Print("b") default: fmt.Print("c") }- a
- ab
- abc
- Nothing, because without break the switch does not compile
Clamp a range
Write
Clamp(v, lo, hi int) int. Ifvis less thanlo, returnlo. Ifvis greater thanhi, returnhi. Otherwise returnv. Assume thatlois not greater thanhi.Scope
Where does the variable
errexist when it is declared asif err := load(); err != nil?- In the whole function
- Only inside this if and its else
- Until the end of the package
- Only on the condition line, but not in the body of the if