Video Coming Soon...
10: Flow Control: switch
WARNING This exercise is in DRAFT status, so there may be errors. If you find any, please email me at help@learncodethehardway.com so I can fix them.
A switch
statement is similar to an if
but it simplifies testing multiple variants of a variable. If you would write this:
x = 10
if x == 1 {
// do something
} else if x == 2 {
// do something
} else {
// something else
}
Then a switch
is better. You would rewrite the above like this:
x = 10
switch x {
case 1:
// do something
case 2:
// do something
default:
// something else
}
This makes it easier to see all the possible branches by their case
, know that there's a default, and reduces the amount you have to type. You can also use a switch
like a "super if
":
j = 10
swith {
case j == 1:
// it's 1
case j == 2:
// it's 2
}
One important thing to remember about switch
is that its case
statements do not have fallthrough. In other languages you have to add a break
to prevent the switch from running the next case like this:
// this is c code!
swith(x) {
case 10:
printf("10");
break
case 20:
printf("20");
break
default:
println("something else");
}
If you remove that first break
then a language like C (or any others) would print out "10 20". Go made the right decision and breaks by default so you don't have to constantly remember this. If you do want this fallthrough behavior then there's the fallthrough
keyword. Just place it after any block you want to...fallthrough.
The Code
Here's code that demonstrates the switch
.
View Source file ex10/main.go Only
package main
import (
"fmt"
)
func main() {
fruit := "Apple"
switch fruit {
case "Apple":
fmt.Println("You have Apples.")
case "Orange":
fmt.Println("You have Oranges.")
case "Grape":
fmt.Println("You have Grapes.")
case "Durian":
fmt.Println("You have Durian.")
default:
fmt.Println("You have some fruit.")
}
// you can also use a switch like a "super if"
i := 23
switch {
case i < 20:
fmt.Println("I is less than 20")
case i > 20:
fmt.Println("I is greater than 20")
default:
fmt.Println("Then what is i now?")
}
}
The Breakdown
I'm going to assume you know that a }
ends a block started by {
and will only describe the other lines. I'm also going to skip the print lines since I've described those enough.
fruit := "Apple"
-- Create a variable to use in theswitch
namedfruit
.switch fruit {
-- Start theswitch
withfruit
as the test.case "Apple":
-- Iffruit
is"Apple"
then run this one.case "Orange":
-- Iffruit
is"Orange"
then run this one.case "Grape":
-- Iffruit
is"Grape"
then run this one.case "Durian":
-- Iffruit
is"Durian"
then run this one. Have you ever had Durian?default:
-- If nothing else matches then this is run.i := 23
-- Create a variablei
with a value of23
.switch {
-- Notice there's nothing given to theswitch
.case i < 20:
-- Sinceswitch
has nothing for its test we do the test here. If it passes becausei
is less than20
, this is run.case i > 20:
-- And ifi
is greater than20
this one is run.default:
-- Otherwise this is run.
Make sure you understand every line of this code before continuing.
The Practice
As usual we'll do the three things that'll make you a better programmer:
- Break It -- You need to learn what error messages mean and what causes them, so break this code on purpose in as many ways as possible.
- Change It -- Try to craft as many different loops as possible. Take this as a game and try to make the most horrendous contraption imaginable. Can you throw some
goto
in the middle of a loop with anif
that goes to random places? - Remake It -- Write up a description of the code, hide or delete this, then try to recreate it using the process from Exercise 04: How to Write Code. Try to do this from memory as much as possible.
Study Drills
- Write a
switch
that usesfallthrough
on purpose so you know how it works. - Put an
if
inside one of thecase
block to see how that works. - Put the
switch
inside afor
loop. - What happens if you put a
goto
in one of thecase
blocks?
Register for Learn Go the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.