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
- Each
deferis registered when its line is reached, not when it runs. - At scope exit they fire last-declared first: pour the cup, then kettle off.
- The pattern keeps acquisition and release adjacent in the source.
Keywords and builtins used here
deferimportpackageproc
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.
Step 1 of 3 in Idioms, step 16 of 27 in Language basics.