if and switch
So far every line of a program runs. But often it should depend: show "Pass" only if the score is high enough, take an umbrella only if it rains. That's what if is for:
1package main2 3import "fmt"4 5func main() {6 score := 727 if score >= 60 {8 fmt.Println("Pass")9 }10 fmt.Println("Score:", score)11}
Pass Score: 72
score >= 60 is a condition: it comes out true or false. If it's true, the block in the curly braces runs; if it's false, the block is skipped. Change 72 to 55 and run it again.
The comparison operators:
| Write | Means |
|---|---|
a == b | equal (two equals signs) |
a != b | not equal |
a < b, a <= b | less than, less than or equal |
a > b, a >= b | greater than, greater than or equal |
else and else if
else means "otherwise". You can put several else ifs in between. Go checks the conditions from top to bottom and runs the block of the first one that is true; it doesn't look at the rest:
1package main2 3import "fmt"4 5func main() {6 temp := 187 if temp >= 26 {8 fmt.Println("Hot: turn on the AC")9 } else if temp >= 16 {10 fmt.Println("Just right")11 } else {12 fmt.Println("Cold: wear a coat")13 }14}
Just right
Press Step to see which conditions it checks. Note that } else { goes on one line: put else on the line after the }, and Go adds a semicolon after the }, so the program doesn't compile.
What does this show?
1package main2 3import "fmt"4 5func main() {6 score := 957 if score >= 60 {8 fmt.Println("Pass")9 } else if score >= 90 {10 fmt.Println("Excellent")11 }12}
95 makes the first condition, score >= 60, true, so it shows "Pass" and never looks at the else if. Put the strictest condition first: ask >= 90, then >= 60.
No parentheses, but braces
The condition needs no parentheses: write if score >= 60, not if (score >= 60) (that runs too, but gofmt removes them). The curly braces, though, are required, even around a single line:
1package main2 3import "fmt"4 5func main() {6 price := 1207 if price > 1008 fmt.Println("Over 100")9}
# command-line-arguments
./prog.go:8:26: syntax error: unexpected newline, expected { after if clauseThe error points at the end of line 8: the compiler read all the way there without finding the { that must follow an if. Add { after the condition and } on a line after the fmt.Println, and it works.
And, or, not
You can combine conditions: && is "and", true only when both sides are; || is "or", true when either side is; ! is "not", which flips true and false.
1package main2 3import "fmt"4 5func main() {6 temp := 227 raining := false8 if temp >= 18 && !raining {9 fmt.Println("Go to the park")10 }11 if temp < 5 || raining {12 fmt.Println("Stay at home")13 }14}
Go to the park
raining is a bool, so it can be the condition by itself; no need for raining == true. Change raining to true and try again.
if with a short statement
An if can start with a short statement, then a semicolon, then the condition. A variable declared there exists only inside that if and its else:
1package main2 3import "fmt"4 5func main() {6 price, count := 35, 37 if total := price * count; total >= 100 {8 fmt.Println("Total:", total, "free shipping")9 } else {10 fmt.Println("Total:", total, "shipping $10")11 }12}
Total: 105 free shipping
After the if, total is gone. Add fmt.Println(total) at the end and the compiler says undefined: total. That keeps short-lived variables from piling up.
switch
When one value is compared with many, switch reads better than a long run of else if. A case can list several values with commas; if none matches, default runs:
1package main2 3import "fmt"4 5func main() {6 day := 67 switch day {8 case 1, 2, 3, 4, 5:9 fmt.Println("Weekday")10 case 6, 7:11 fmt.Println("Weekend")12 default:13 fmt.Println("No such day")14 }15}
Weekend
Unlike C or Java, a Go case leaves the switch when it's done; you don't write break.
How many lines does this show?
1package main2 3import "fmt"4 5func main() {6 size := "M"7 switch size {8 case "S":9 fmt.Println("Small")10 case "M":11 fmt.Println("Medium")12 case "L":13 fmt.Println("Large")14 }15}
size is "M", so only the case "M" block runs: it shows "Medium" and leaves the switch. Go doesn't carry on into case "L".
switch with no condition
Write nothing after switch, and each case is a condition. Like if, it runs the first one that is true, from the top:
1package main2 3import "fmt"4 5func main() {6 score := 857 switch {8 case score >= 90:9 fmt.Println("A")10 case score >= 80:11 fmt.Println("B")12 case score >= 60:13 fmt.Println("C")14 default:15 fmt.Println("D")16 }17}
B
It's another way to write a long if/else if chain, and it reads like a table. If you really want to go on into the next case, end the case with fallthrough, but you'll rarely need it.
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it.
Pass or retake
✓For each of two scores, show score pass for 60 or more and score retake for less than 60. It should show 72 pass and 55 retake.
72 pass 55 retake
1package main2 3import "fmt"4 5func main() {6 score := 727 fmt.Println(score)8 score = 559 fmt.Println(score)10}
Fix it: else on its own line
✓This program doesn't compile. Fix it so it shows Turn on the AC and Open a window.
Turn on the AC Open a window
1package main2 3import "fmt"4 5func main() {6 temp := 287 if temp > 25 {8 fmt.Println("Turn on the AC")9 }10 else {11 fmt.Println("Open a window")12 }13 temp = 1814 if temp > 25 {15 fmt.Println("Turn on the AC")16 }17 else {18 fmt.Println("Open a window")19 }20}
Shipping by weight
✓Shipping costs $8 up to 1 kg, $15 up to 5 kg, and $30 for anything heavier. Use a switch with no condition to set fee, and show 3 kg costs 15 and 12 kg costs 30.
3 kg costs 15 12 kg costs 30
1package main2 3import "fmt"4 5func main() {6 weight := 37 fee := 08 fmt.Println(weight, "kg costs", fee)9 weight = 1210 fmt.Println(weight, "kg costs", fee)11}
What you learned
if condition { … }runs the block only when the condition is true;else ifandelsefollow, and only the first true block runs.- No parentheses around the condition, braces always, and
} else {on one line. &&is and,||is or,!is not.- A variable declared in
if x := …; condition { … }exists only in thatifand itselse. - A
switchcase leaves when it's done, nobreakneeded; a case can list several values, anddefaultruns when none match. - A
switchwith no condition makes eachcasea condition, replacing a longifchain;fallthroughcarries on into the next case.