defer lowers. crates/atoll/tests/deferred_work_runs_on_every_exit.rs is
the run oracle: registered work runs on every exit of the lexical scope,
last registered first, including early returns. For a value that must be
released, Drop is still the mechanism that owns the bytes — defer is
the extra work around that, not a replacement for it.
defer expression schedules work for the exit of the current lexical scope
— the block the defer is written in, not necessarily the whole function.
error IoError { Denied }
struct Handle { id int }
impl Handle {
fn open(name string) Handle ! IoError {
if name.is_empty() { error Denied }
return Handle { id: name.len() }
}
fn read(&self) string ! IoError { return "payload" }
fn close(&self) void { println("closed ${self.id}") }
}
fn process(name string) int ! IoError {
handle := Handle.open(name)?
defer handle.close()
body := handle.read()?
return body.len()
}close runs on the propagated ? from read and on the return — after the
return value has been evaluated, so the return expression can still read the
resource it is about to release. A deferred write to what the result was read
from is too late to change it:
fn main() int {
mut n := 1
defer n = 2
return n // 1: the result is taken, then the defer runs
}A defer that only reads a value the result moved reads it where the result now holds it, so it sees what the caller receives. The same holds for a block’s value, and for a value moved into a field of a struct or variant built in the result:
fn label() string {
s := "abc"
defer println("closing ${s}") // closing abc
return s
}
fn main() int {
t := {
s := "de"
defer println("leaving ${s}") // leaving de
s
}
return label().len() + t.len()
}The defer may not write that value or move it out, since the result has
already taken it. A value the result’s expression hands to a call, as in
return give(s).len(), may be gone by then, and a defer reading it is refused.
What the result took is the value, not the block a ^T in it points at.
A defer may write through such a pointer: the write lands in the block,
which the caller receives with the pointer.
struct Cell { n int }
struct Wrap { c ^Cell, k int }
fn make() Wrap {
mut w := Wrap { c: ^Cell { n: 10 }, k: 2 }
defer w.c.^.n = 30 + w.k // writes the block the result points at
return w
}
fn main() int {
return make().c.^.n // 32
}Another way to the block (a second ^T in the value, a copy of the pointer
taken before, a value handed to a call that holds one) sees the write where
the same line written before the return would:
struct Cell { n int }
struct Wrap { c ^Cell, k int }
fn make(log ^Cell) Wrap {
mut w := Wrap { c: log, k: 1 }
defer w.c.^.n = log.^.n + 20 // `log` reaches the same block
return w
}
fn main() int {
log := ^Cell { n: 10 }
w := make(log)
return log.^.n + w.k // 31: the caller's pointer sees the write
}A defer that only reads through pointers reads each block as it is when it reads it.
Registration is dynamic
A defer registers only when execution reaches it. A defer in a branch that is
not taken never registers, and the cleanup belongs to that branch’s block.
struct Span { name string }
impl Span {
fn start(name string) Span { return Span { name: name.clone() } }
fn finish(&self) void { println("finish ${self.name}") }
}
fn execute() int { return 7 }
fn run(tracing bool) int {
if tracing {
span := Span.start("run")
defer span.finish()
return execute()
}
return execute()
}The span finishes when the if branch is left — through the return here, or
at the closing brace if the branch fell through instead.
That also means acquisition and registration must be adjacent. Register immediately after success: before it, there is no valid resource; long after it, a new early exit can slip in between and bypass registration.
error NetError { Refused }
struct Conn { id int }
impl Conn {
fn connect(address string) Conn ! NetError {
if address.is_empty() { error Refused }
return Conn { id: address.len() }
}
fn write_all(&self, payload string) int ! NetError { return payload.len() }
fn close(&self) void { println("closed ${self.id}") }
}
fn send(address string, payload string) int ! NetError {
conn := Conn.connect(address)?
defer conn.close()
return conn.write_all(payload)?
}Ordering
Defers registered in one scope run in reverse order — last in, first out.
fn first_cleanup() void { println("first") }
fn second_cleanup() void { println("second") }
fn f() void {
defer first_cleanup()
defer second_cleanup()
println("body")
}That prints body, second, first.
When several scopes are left at once, the innermost is cleaned first, and within each scope the order is still LIFO.
fn note(message string) void { println(message) }
fn f() void {
defer note("outer")
{
defer note("inner first")
defer note("inner second")
note("body")
}
note("after block")
}Output: body, inner second, inner first, after block, outer.
The same order, as a value:
fn main() int {
mut t := 0
{
defer t = t * 10 + 1
{
defer t = t * 10 + 3
defer t = t * 10 + 2
t = 4
}
}
return t // 4, then 42 and 423 at the inner brace, then 4231
}Acquisition order therefore produces the correct reverse release order for free:
error E { Failed }
struct Outer { id int }
struct Inner { id int }
impl Outer {
fn acquire() Outer ! E { return Outer { id: 1 } }
fn acquire_inner(&self) Inner ! E { return Inner { id: self.id + 1 } }
fn release(&self) void { println("release outer") }
}
impl Inner {
fn release(&self) void { println("release inner") }
}
fn work() int ! E {
outer := Outer.acquire()?
defer outer.release()
inner := outer.acquire_inner()?
defer inner.release()
return inner.id
}inner releases before outer on every exit path.
A block’s defers and the values it holds unwind together, in reverse: a
defer runs before the values declared ahead of it are released, and after
those declared behind it (Destruction).
One defer per iteration
A loop body is a lexical scope, so a defer in it belongs to that iteration —
including on continue and on the break that ends the loop.
error IoError { Denied }
struct File { id int }
impl File {
fn open(path &string) File ! IoError {
if path.is_empty() { error Denied }
return File { id: path.len() }
}
fn read(&self) string ! IoError { return "line" }
fn close(&self) void { println("closed ${self.id}") }
}
fn total_size(paths []string) int ! IoError {
mut total := 0
for path in paths {
file := File.open(path)?
defer file.close()
body := file.read()?
if body.is_empty() {
continue
}
if body == "STOP" {
break
}
total += body.len()
}
return total
}Each file closes before the next iteration opens one. A defer written outside
the loop would instead hold every handle until the surrounding scope ends —
which is exactly the shape that exhausts a file-descriptor budget.
What the deferred expression sees
The expression runs at scope exit and reads the lexical places it names at that moment, not at registration time.
fn f() int {
mut count := 0
defer println("count=${count}")
count = 3
return count
}That prints count=3. To preserve a specific value, bind an immutable snapshot
and defer on that instead:
fn report_start(value int) void { println("started at ${value}") }
fn f(count int) int {
starting_count := count
defer report_start(starting_count)
return count + 1
}The values a deferred expression needs stay live until it runs. Deferring on a large buffer therefore extends that buffer’s lifetime to the end of the scope on purpose; introduce a small snapshot when only a scalar is needed.
A defer may take a block when the cleanup has several steps, though a named
function usually reads better:
fn stop_timer() void { println("timer stopped") }
fn flush_metrics() void { println("metrics flushed") }
fn f() int {
defer {
stop_timer()
flush_metrics()
}
return 1
}Taking and replacing a value
A defer is checked, and runs, as its body written out at each way out that runs it. So it may move a value from outside it, or write one whole:
- A value a defer moves must hold its value on every way out the defer runs on. After the run it is gone: nothing releases it, and neither code past the block nor a later defer can read it.
- A value a defer writes whole releases its old value at the write, after the right side, and is released at its own place, holding what the defer wrote. Where it was moved before the defer ran, the write fills it.
- A defer that moves a value on some ways only leaves it held on the others, and it is released at its own place there.
fn send(lines []string) int { return lines.len() }
fn main() int {
mut sent := 0
{
buf := ["a", "b", "c"]
defer sent = send(buf) // moves `buf` at the brace
}
return sent
}struct Cell { n int }
struct Tag { id int, log ^Cell }
impl Drop for Tag {
fn drop(&mut self) void { self.log.^.n = self.log.^.n * 10 + self.id }
}
fn run(log ^Cell) int {
mut t := Tag { id: 1, log: log }
{
defer t = Tag { id: 2, log: log } // releases tag 1, after the right side
}
return t.id * 100 + log.^.n // 201; tag 2 is released after
}
fn main() int {
log := ^Cell { n: 0 }
first := run(log)
return first * 10 + log.^.n // 2010 + 12
}The defer in run builds tag 2, then releases tag 1, so the log reads 1
when run returns 201; tag 2 is released at run’s end, after its result
is read, and the log reads 12.
struct Cell { n int }
struct Tag { id int, log ^Cell }
impl Drop for Tag {
fn drop(&mut self) void { self.log.^.n = self.log.^.n * 10 + self.id }
}
fn keep(t Tag) int { return t.id * 100 }
fn run(b bool, log ^Cell) int {
t := Tag { id: 1, log: log }
mut n := 0
{
defer if b { n = keep(t) } // moves `t` on one arm
}
return n + log.^.n
}
fn main() int {
a := ^Cell { n: 0 }
b := ^Cell { n: 0 }
return run(true, a) * 10 + run(false, b)
}front-run=1010 marks an answer the new compiler gives. With b true the
defer hands t to keep, which releases it, so run reads the log as 1
and returns 101. With b false t is still held, to run’s brace, so
the log reads 0 when run returns. Today’s compiler releases t where
the arms meet and answers 1011.
A defer in a loop runs once a turn, so one that moves a value declared outside the loop moves it again on the next turn, as a plain move there would:
fn send(lines []string) int { return lines.len() }
fn main() int {
buf := ["a"]
mut n := 0
for i in 0..2 {
defer n += send(buf) // the second turn's run moves `buf` again
}
return n
}And a value a defer moved is gone past the block whose end ran it:
fn send(lines []string) int { return lines.len() }
fn main() int {
buf := ["a"]
mut n := 0
{
defer n = send(buf)
}
return n + buf.len() // `buf` was moved by the defer at the brace
}front-fail=ATOLL3102 marks a refusal the new compiler gives. Today’s
compiler takes both and answers 2.
Fallible cleanup
Postfix ? is rejected inside a deferred expression. The surrounding exit is
already underway, so there is no caller continuation for a cleanup failure to
propagate to.
error E { Failed }
fn maybe_close() int ! E { error Failed }
fn f() int ! E {
defer maybe_close()?
return 1
}The diagnostic is explicit: `?` cannot propagate out of a `defer` — handle errors inline with `match` or `catch`. Pick a policy and write it out:
error E { Failed }
fn maybe_close() int ! E { error Failed }
fn report_cleanup(message string) void { println(message) }
fn f() int {
defer match maybe_close() {
Ok(_) => {}
Err(err) => report_cleanup("cleanup failed")
}
return 1
}For a cleanup whose failure is genuinely ignorable, the Result methods are
shorter:
error E { Failed }
fn maybe_close() int ! E { error Failed }
fn f() int {
defer maybe_close().unwrap_or(0)
return 1
}Choose deliberately — log it, record it, retry safely, or ignore a documented idempotent close failure. Do not silently discard a transactional error.
errdefer
errdefer registers work as defer does, and runs it only when its scope is
left without success:
- by an error leaving the function: a
?on an error, anerror Xstatement, or areturnof an error value; - by the task’s cancellation unwinding through the scope, for an
errdeferthat binds no error (below).
A brace, a break, a continue and a successful return, one in a catch
arm included, discard it. A trap runs neither kind
(Panics). In a closure, it is the closure’s own
result that counts.
error SlotError { Full }
struct Slots { used int, cap int }
impl Slots {
fn reserve(&mut self) int ! SlotError {
if self.used == self.cap { error Full }
self.used += 1
return self.used
}
fn give_back(&mut self) void { self.used -= 1 }
}
fn check(id int) int ! SlotError {
if id > 1 { error Full }
return id
}
fn open(s &mut Slots) int ! SlotError {
id := s.reserve()?
errdefer s.give_back() // runs only when an error leaves `open`
return check(id)?
}
fn main() int {
mut s := Slots { used: 0, cap: 4 }
a := open(&mut s).unwrap_or(0) // succeeds: the errdefer is discarded
b := open(&mut s).unwrap_or(0) // `check` fails: the slot is given back
return a * 100 + b * 10 + s.used // 1, 0 and 1
}planned marks a design not built yet. Today’s compiler does not know
errdefer (ATOLL1009); the new compiler takes it with its error channel.
Written out by hand, it is a mut ok flag set before each successful
return, and a return added later forgets to set it. Ownership already
releases what the scope owns on an error; errdefer is for the compensations
that are not ownership: give back a reservation, remove a file the function
made, unregister, mark a span failed.
Defers and errdefers share one list: last registered first, brace by brace,
and then the scope’s releases. A defer’s rules hold for an errdefer: no ?,
return, break or continue out of it, and no suspension. It is checked
only on the ways it runs on, so x := reserve()?; errdefer x.undo(); …; return x is taken: the successful return moves x, and the errdefer never
runs there.
errdefer e => body binds e, a &E of the error the function returns.
errdefer { arms } takes catch’s arms over E, a union’s member types
included, each binding by reference. The arms need not cover every error: an
errdefer makes no value, so an error no arm matches runs nothing, and an arm
no error can reach is the unreachable-arm lint. A brace whose first item is
pattern => holds arms; any other brace is a block.
A cancel has its own arm. Cancellation is not an error
(Cancellation):
a cancel has no error to bind, and no error type gains a variant for it. A
cancel runs an errdefer that binds nothing, and the cancel arm of one with
arms; errdefer e => … never runs on a cancel. cancel is a keyword only
among an errdefer’s arms, where it matches no error and binds nothing; _
and a binding arm match errors only.
import time
error CreateError {
NotFound
Denied
}
fn log(line string) void { println(line) }
fn count_failure(e &CreateError) void { }
fn find(name &string) int ! CreateError {
if name.is_empty() { error NotFound }
return name.len()
}
fn create(name string) int ! CreateError {
errdefer e => count_failure(e) // an error, never a cancel
errdefer {
NotFound => log("no template named ${name}")
cancel => log("create cancelled")
}
time.sleep(time.Duration.of_millis(1)) // a cancel can leave here
return find(&name)?
}An errdefer that can never run is refused: its function returns no error and
never suspends. A cancel arm in a scope no cancel can leave is the
unreachable-arm lint, not an error, since whether a scope suspends is
inferred.
Suspension
A deferred body may not suspend. A defer runs on every exit, and a
cancelled task’s exit is one of them: the task is already being torn down
there, and a suspension in the middle of that would be a second scheduling
decision taken while the first is still being carried out. A deferred call to
anything that can suspend is refused (ATOLL1071), however its scope ends. A
Drop body follows the same rule
(Cancellation).
fn flush() void { println("flushed") }
fn f() int {
defer flush()
return 1
}Work that has to wait, such as a flush to the network or a commit, belongs on the normal path, where the code knows the work finished. Keep cleanup a local, synchronous, idempotent release.
When not to use defer
The compiler already inserts value destruction, reference-count maintenance,
weak-reference updates, and user Drop dispatch at the right exit points.
Ordinary memory hygiene needs no defer.
Use defer when the paired action is a semantic operation you want visible in
the source:
- close a host handle;
- finish a tracing span;
- restore temporary process or task state;
- release a manually acquired external lease;
- run a best-effort compensating action.
Use a transaction block for database commit/rollback rather than
reimplementing it with deferred SQL. And do not treat defer as a durability
guarantee: hard runtime teardown and host-process failure are outside ordinary
source control flow.
If ownership of a resource transfers to another value, make that transfer explicit so two cleanup paths do not both claim responsibility for it.
Putting it together
error JobError {
Unreachable { host: string }
Rejected { code: int }
}
struct Lease { host string }
struct Span { name string }
impl Lease {
fn acquire(host &string) Lease ! JobError {
if host.is_empty() { error Unreachable { host: host.clone() } }
return Lease { host: host.clone() }
}
fn release(&self) void { println("released ${self.host}") }
fn submit(&self, item int) int ! JobError {
if item < 0 { error Rejected { code: item } }
return item
}
}
impl Span {
fn start(name string) Span { return Span { name: name.clone() } }
fn finish(&self) void { println("span ${self.name} done") }
}
fn run_job(host string, items []int, budget int) int ! JobError {
span := Span.start("run_job")
defer span.finish()
lease := Lease.acquire(host)?
defer lease.release()
mut accepted := 0
for item in items {
item_span := Span.start("item")
defer item_span.finish()
if item == 0 {
continue
}
if accepted >= budget {
break
}
accepted += lease.submit(item)?
}
return accepted
}The per-item span finishes once per iteration — on continue, on break, and
on the propagated error from submit. When that error propagates, cleanup runs
innermost-first: the item span, then the lease, then the job span, and only then
does the JobError reach the caller.