Switch Statements in Go
Table of Contents
Switch statements are a way to compare a value against multiple options. They are similar to if-else statements but are more concise and readable when the number of options is more than 2.
All the content from our Boot.dev courses are available for free here on the blog. This one is the "Conditionals" chapter of Learn Go. If you want to try the far more immersive version of the course, do check it out!
func getCreator(os string) string {
var creator string
switch os {
case "linux":
creator = "Linus Torvalds"
case "windows":
creator = "Bill Gates"
case "mac":
creator = "A Steve"
default:
creator = "Unknown"
}
return creator
}
Notice that in Go, the break statement is not required at the end of a case to stop it from falling through to the next case. The break statement is implicit in Go.
Fallthrough
If you do want a case to fall through to the next case, you can use the fallthrough keyword.
func getCreator(os string) string {
var creator string
switch os {
case "linux":
creator = "Linus Torvalds"
case "windows":
creator = "Bill Gates"
// all three of these cases will set creator to "A Steve"
case "macOS":
fallthrough
case "Mac OS X":
fallthrough
case "mac":
creator = "A Steve"
default:
creator = "Unknown"
}
return creator
}
Default
The default case does what you'd expect: it's the case that runs if none of the other cases match.
Frequently Asked Questions
What is a switch statement in Go?
A switch statement compares a value against multiple options. It is more concise and readable than if-else statements when there are more than two options.
Does a Go switch statement need break?
No. The break statement is implicit in Go, so a case does not fall through to the next case automatically.
How do you make a Go switch case fall through?
Use the fallthrough keyword when you want a case to fall through to the next case.
What does default do in a Go switch statement?
The default case runs if none of the other cases match.
