switch, every form in Go
Go's switch takes no condition, several values per case, or an initializer.
func classify(n int) string {
switch {
case n < 0:
return "negative"
case n == 0:
return "zero"
}
switch n {
case 1, 2, 3:
return "small"
case 4:
fallthrough
case 5:
return "medium"
}
switch day := n % 7; day {
case 0, 6:
return "weekend-ish"
default:
return "large"
}
}
How it works
- A conditionless switch is a tidy if-else chain.
fallthroughis explicit, because cases do not fall through.- An initializer scopes a variable to the switch.
Keywords and builtins used here
casedefaultfallthroughfuncintreturnstringswitch
The run, in numbers
- Lines
- 24
- Characters to type
- 272
- Tokens
- 69
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 49 seconds.
Step 2 of 4 in Control flow, step 7 of 30 in Language basics.