typestar

switch in Odin

Two switches: one on a value with lists and ranges, one bare as an if-else ladder.

package main

import "core:fmt"

main :: proc() {
    // switch breaks by default; cases take lists and ranges.
    switch cloud_eighths := 3; cloud_eighths {
    case 0, 1, 2: fmt.println("clear enough to sail")
    case 3..=5:   fmt.println("broken cloud, watch it")
    case:         fmt.println("overcast, compass out")
    }

    // A bare switch is a cleaner if-else ladder.
    depth := 42
    switch {
    case depth <= 10: fmt.println("snorkel water")
    case depth <= 40: fmt.println("open-water dive")
    case:             fmt.println("plan your stops")
    }
}

How it works

  1. switch cloud_eighths := 3; cloud_eighths scopes its subject like if does.
  2. Cases take lists (0, 1, 2) and ranges (3..=5), and break by default.
  3. A bare switch with boolean cases reads cleaner than a chain of else-ifs.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
522
Tokens
103
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 88 seconds.

Type this snippet

Step 3 of 3 in Control flow, step 6 of 27 in Language basics.

← Previous Next →

switch in other languages