typestar

if and when in Odin

if with an init statement scopes the wind reading; when branches at compile time.

package main

import "core:fmt"

main :: proc() {
    // if takes an optional init statement before the condition.
    if wind := 26; wind > 33 {
        fmt.println("gale: stay in harbor")
    } else if wind > 21 {
        fmt.println("reef the main and go")
    } else {
        fmt.println("fair wind, full sail")
    }

    // when is if at compile time -- the false branch never compiles.
    when ODIN_OS == .Linux {
        fmt.println("forecast served from a linux box")
    }
}

How it works

  1. if wind := 26; wind > 33 declares the value for exactly this chain.
  2. else if and else complete the sailing call.
  3. when ODIN_OS == .Linux is compile-time: the false branch never compiles at all.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
422
Tokens
74
Three-star pace
75 tpm

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

Type this snippet

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

← Previous Next →