typestar

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

  1. if/else if returns early per branch.
  2. A bare switch acts as an if-else chain.
  3. default covers the remaining cases.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 4 in Control flow, step 6 of 30 in Language basics.

← Previous Next →