typestar

defer in Odin

Cleanup declared next to the thing it cleans: defer runs at scope exit, in reverse.

package main

import "core:fmt"

brew :: proc() {
    // defer runs at scope exit, last-declared first.
    fmt.println("kettle on")
    defer fmt.println("kettle off")
    defer fmt.println("pour the cup")
    fmt.println("three minutes steeping")
}

main :: proc() {
    brew()
    fmt.println("milk first, obviously")
}

How it works

  1. Each defer is registered when its line is reached, not when it runs.
  2. At scope exit they fire last-declared first: pour the cup, then kettle off.
  3. The pattern keeps acquisition and release adjacent in the source.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
294
Tokens
66
Three-star pace
75 tpm

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

Type this snippet

Step 1 of 3 in Idioms, step 16 of 27 in Language basics.

← Previous Next →

defer in other languages