Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
To choose between several options with "if" / "else" statements, you'd have to nest them several deep, which is hard to read. So like most programming languages, Go offers a "switch" statement. You specify the expression you want to switch on, "case" statements with possible values for that expression, and one or more lines of code that should run in each case.
- To choose between several options with
if
/else
statements, you'd have to nest them several deep, which is hard to read - So like most programming languages, Go offers a
switch
statement. - You specify the expression you want to switch on, case statements with possible values for that expression, and one or more lines of code that should run in each case.
- You can add a
default
case at the end, that will run if none of the other cases match.
package main
import (
"fmt"
)
func main() {
fmt.Print("You win: ")
doorNumber := 2
switch doorNumber {
case 1:
fmt.Println("a new car!") // not printed
case 2:
fmt.Println("a llama!") // printed
default:
fmt.Println("a goat!") // not printed
}
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up