Defer
Scope-based cleanup, ordering, capture, unwinding, and restrictions.
Contents
defer registers a call or block to run when the current scope exits.
Forms#
A defer takes either a single call or a block.
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 a call expression; defer 1 + 2 is rejected.
Execution Time#
A defer runs when control leaves the scope in which it was registered: normal fallthrough, return, break, continue, a propagated ?, or 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 it. It can 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#
A defer captures the lexical binding visible at registration time, not a later shadowing declaration. The value read by the call is the value at execution time.
fn show(n i32) {
print(n)
}
fn main() {
var x = 1
defer show(x)
x = 2
print("body")
}
The output is body, then 2.
fn main() {
defer show(100)
const show = 5
print("body")
}
The deferred call refers to the function show, not the later local binding. Name resolution happens at registration.
Loops#
A loop body is a scope. A defer in 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.
fn main() {
for i in 0..3 {
defer print($"cleanup {i}")
print(i)
}
}
Error Propagation#
When ? propagates an error, every scope between the expression and the enclosing function return is exited in order, and each scope's defers run.
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.
Restrictions#
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 entirely inside the defer body, but may not jump out of the defer.
fn invalid() {
defer {
return // error: cannot return from inside a defer body
}
}
? is rejected inside a defer body. 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.
Managed Values#
A defer may capture managed values. The compiler keeps captured values reachable while the defer is registered, and deferred code participates in root tracking.
fn announce(n i32) {
defer {
const message = $"finished with {n}"
print(message)
}
print("working")
}
Use#
Use defer when a scope acquires something that must be released on every exit path, or when several operations form one teardown. Do not use it to hide ordinary sequencing. Do not rely on a defer to change a return value.