Defer

Defer schedules cleanup code to run when the current scope exits, regardless of how it exits - normal completion, early return, fail, or error propagation. Multiple defers execute in reverse (LIFO) order.

defer runs cleanup code when the scope exits. It fires on normal return, early return, fail, and ? propagation.

fn process() {
  println("start")
  defer println("cleanup")
  println("work")
}

Multiple defers run in reverse (LIFO) order.

fn multi() {
  defer println("third")
  defer println("second")
  defer println("first")
  println("body")
}

Defer blocks can contain multiple statements.

fn with_block() {
  defer {
    println("step 1")
    println("step 2")
  }
  println("main work")
}

Defer in a loop runs at each iteration end.

fn in_loop() {
  for i in range(3) {
    defer println("cleanup {i}")
    println("iteration {i}")
  }
}

fn main() {
  process()
  println("---")
  multi()
  println("---")
  with_block()
  println("---")
  in_loop()
}
$ pyr run defer.pyr
start
work
cleanup
---
body
first
second
third
---
main work
step 1
step 2
---
iteration 0
cleanup 0
iteration 1
cleanup 1
iteration 2
cleanup 2