Conditionals and switch in Go
Branching, including switch with no condition.
func classify(n int) string {
if n < 0 {
return "negative"
} else if n == 0 {
return "zero"
}
switch {
case n < 10:
return "small"
case n < 100:
return "medium"
default:
return "large"
}
}
How it works
if/else ifreturns early per branch.- A bare
switchacts as an if-else chain. defaultcovers the remaining cases.
Keywords and builtins used here
casedefaultelsefuncifintreturnstringswitch
The run, in numbers
- Lines
- 16
- Characters to type
- 189
- Tokens
- 47
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 33 seconds.
Step 1 of 4 in Control flow, step 6 of 30 in Language basics.