capypad
0 day streak
go / beginner
Snippet

Switch Statements in Go

Go's switch is more flexible than in many languages. It can compare against values or conditions without an expression. Cases don't fall through by default (no break needed), but you can use `fallthrough` to continue. Multiple values in a single case are separated by commas. The expression can be declared inline as shown with `day := time.Now().Weekday()`.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main
 
import (
"fmt"
"time"
)
 
func grade(score int) string {
switch {
case score >= 90:
return "A"
case score >= 80:
return "B"
case score >= 70:
return "C"
default:
return "F"
}
}
 
func main() {
switch day := time.Now().Weekday(); day {
case time.Saturday, time.Sunday:
fmt.Println("Weekend!")
default:
fmt.Println("Weekday:", day)
}
 
fmt.Println("Score 85:", grade(85))
}
Breakdown
1
switch {
Switch without expression evaluates boolean conditions
2
case score >= 90:
Condition-based case using comparison operators
3
return "A"
No fallthrough - execution stops after matching case
4
case time.Saturday, time.Sunday:
Multiple values in one case separated by comma
5
switch day := time.Now().Weekday(); day {
Inline variable declaration in switch statement