Contents

defer registers a call or block to run when the current scope exits. It is the language's structured replacement for manual teardown, and it works with early return, loop control, and error propagation.

Forms#

A defer takes either a single call or a block. The call form is concise for one cleanup operation. The block form groups several operations that belong to the same scope.

fn write_report(path str) Result[bool, str] {
    defer print("report finished")
    return Success(true)
}
fn use_resources(first Resource, second Resource) {
    defer {
        first.deinit()
        second.deinit()
    }
    print("using resources")
}

A defer must be a statement inside a function or block. It cannot appear at module scope. The call form requires an actual call expression; defer 1 + 2 is rejected.

Execution Time#

A defer runs when control leaves the scope in which it was registered. That includes normal fallthrough to the end of the block, return, break, continue, a propagated ?, and a failed checked construction. The deferred code does not run when the defer statement is reached; only the binding and capture happen then.

fn example() i32 {
    defer print("leaving")
    print("inside")
    return 7
}

The output is inside, then leaving. The return value is computed before the deferred code runs, so a defer cannot change the value that the function returns. It can, however, mutate an outer variable or perform side effects.

Ordering#

Defers in the same scope run in last-in, first-out order. Nested scopes unwind from the inside out. Each loop iteration creates a fresh body scope, so a defer inside a loop runs once per iteration.

fn ordering() {
    defer print("first registered")
    defer print("second registered")
    defer print("third registered")
    print("body")
}

The output is body, third registered, second registered, first registered.

fn nested() {
    defer print("outer")
    {
        defer print("inner")
        print("work")
    }
}

The output is work, inner, outer. A break, continue, or return that leaves several scopes runs every defer on the way out, innermost first.

Capture and Late Evaluation#

A defer captures the lexical binding that is visible at registration time, not a later shadowing declaration. The value read by the call is the value at execution time. This distinction is useful: a defer can observe the final state of a counter, but a later const with the same name does not hijack the call.

fn show(n i32) {
    print(n)
}

fn main() {
    var x = 1
    defer show(x)
    x = 2
    print("body")
}

The output is body, then 2. The defer resolves x to the variable declared before it and reads the current value when the scope exits.

fn main() {
    defer show(100)
    const show = 5
    print("body")
}

The deferred call still refers to the function show, not to the later local binding. Name resolution happens at registration.

Defer and Loops#

A loop body is a scope. A defer inside the body runs at the end of each iteration, including iterations ended by continue or break. A defer registered before a loop runs when the enclosing function or block exits, not after each iteration.

fn main() {
    for i in 0..3 {
        defer print($"cleanup {i}")
        print(i)
    }
}

The output interleaves each iteration's body and cleanup. Nested loops run the inner defer before the outer defer for each outer iteration.

Defer and Error Propagation#

When ? propagates an error, every scope between the expression and the enclosing function returns is exited in order, and each scope's defers run. This makes defer reliable for releasing resources on the failure path.

fn guarded() Result[i32, str] {
    defer print("guarded cleanup")
    const value = fail()?
    return Success(value)
}

If fail() returns Error, the defer runs before guarded returns the error. A failed checked construction behaves the same way: the scope unwinds and the construction returns an error.

Restrictions#

A defer body is executed at scope exit, so control-flow statements that would leave the defer body are restricted. A return inside a defer is rejected because it would override the function's already-computed result. A break or continue may target a loop that is entirely inside the defer body, but it may not jump out of the defer into the surrounding function.

fn invalid() {
    defer {
        return       // error: cannot return from inside a defer body
    }
}

The ? operator is also rejected inside a defer body. A defer runs during unwinding, and propagating a second error from cleanup would obscure the original outcome. Handle the cleanup failure explicitly or perform it before the defer is needed.

A defer may contain another defer. The inner defer runs at the end of the outer defer block, not at the end of the surrounding function.

fn nested() {
    defer {
        print("outer start")
        defer print("inner")
        print("outer end")
    }
    print("body")
}

The output is body, outer start, outer end, inner.

Defer and Managed Values#

A defer may capture managed values. The compiler keeps the captured values reachable while the defer is registered, and the deferred code participates in root tracking in the same way as ordinary code. This is why a defer can safely build a string or call a method on a record after the main body has finished.

fn announce(n i32) {
    defer {
        const message = $"finished with {n}"
        print(message)
    }
    print("working")
}

When to Use Defer#

Use defer when a scope acquires something that must be released, when cleanup must run on every exit path, or when several operations form one logical teardown. Do not use it to hide ordinary sequencing; a plain statement is clearer when cleanup always happens at a known point. Do not rely on a defer to change a return value; compute the value explicitly and let the defer perform side effects.