typestar

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

  1. A conditionless switch is a tidy if-else chain.
  2. fallthrough is explicit, because cases do not fall through.
  3. An initializer scopes a variable to the switch.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Control flow, step 7 of 30 in Language basics.

← Previous Next →