switch and fallthrough
- Go course
- Beginner
- Lesson 38/90
- 4 min
Learn multi-branch switch and the fallthrough behavior.
switch and fallthrough
switch compares a value against several possibilities. A case can take several values separated by commas; the switch ends when the matching case finishes:
switch gun {
case "Cumartesi", "Pazar":
fmt.Println("hafta sonu")
case "Cuma":
fmt.Println("son iş günü")
default:
fmt.Println("iş günü")
}To deliberately continue into the next case write fallthrough; it is rarely needed.
Expressionless switch
A switch without a value is a readable form of a long if-else chain; each case is a bool expression:
switch {
case sicaklik < 0:
fmt.Println("donuyor")
case sicaklik < 20:
fmt.Println("serin")
default:
fmt.Println("sıcak")
}Cases are tried from top to bottom; the first true one runs.
Practice Kind of day
Write gunTuru(gun string) string: "hafta sonu" for "Cumartesi" and "Pazar", "iş günü" otherwise. Print gunTuru("Pazar") and gunTuru("Salı") on one line.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func gunTuru(gun string) string {
switch gun {
case "Cumartesi", "Pazar":
return "hafta sonu"
default:
return "iş günü"
}
}
func main() {
fmt.Println(gunTuru("Pazar"), gunTuru("Salı"))
}Expected output
hafta sonu iş günü
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Does <code>fallthrough</code> check the next case's condition?
- It runs all cases
- It jumps to default
- No; it runs the next case's body without checking its condition Correct answer
- Yes, it runs it if the condition is true
Explanation: fallthrough is an unconditional jump; that's why it can cause surprising behavior and is used carefully.
2 Multiple values
switch gun {
case "Cumartesi"____ "Pazar":
fmt.Println("hafta sonu")
}
switch gun {
case "Cumartesi", "Pazar":
fmt.Println("hafta sonu")
}
Explanation: A case takes several values separated by commas.
3 Input and output
| Term | Meaning |
|---|---|
"Pazar" |
hafta sonu |
"Cuma" |
son iş günü |
"Salı" |
iş günü (default) |
sicaklik = -3 |
donuyor |