switch
switch compares one value against several cases and runs the first one that matches:
choice := 2
switch choice {
case 1: print("play")
case 2: print("load")
case 3: print("settings")
default: print("pick 1 to 3")
}
load
Each case stops on its own; there's no break to forget. default runs when nothing matched, and goes last.
Longer cases
level := 1
switch level {
case 1:
print("starting")
print("good luck")
default:
print("welcome back")
}
starting
good luck
Several values and ranges
fn stage(int age) {
switch age {
case 0 to 12: return "kid"
case 13 to 19: return "teen"
case 65, 66, 67: return "retiring"
default: return "adult"
}
}
print(stage(4), stage(15), stage(40), stage(66))
kid teen adult retiring
to includes both ends.
Chars and strings
key := 'q'
switch key {
case 'w': print("up")
case 's': print("down")
case 'q', 'x': print("quit")
}
cmd := "help"
switch cmd {
case "start": print("go")
case "help", "?": print("showing help")
default: print("unknown: {cmd}")
}
quit
showing help
Without a value
A switch with no value checks conditions in order:
hp := 25
switch {
case hp <= 0: print("dead")
case hp < 30: print("low")
default: print("ok")
}
low
fallthrough
To continue into the next case, end a case with fallthrough:
v := 2
switch v {
case 2:
print("two")
fallthrough
case 3:
print("two or three")
}
two
two or three
Rules
- Case values are fixed when compiling: literals like
1,'q'and"quit", or constants. - A value handled by two cases is a compile error.
breakinside aswitchleaves the loop around it.- When the cases are numbers close together, the switch jumps straight to the right case instead of checking them one by one.