Skip to content

Destruction

A release goes on the path, not at the end of a scope — released on the spot when nothing names the value again, held to the end of the block when something does.

Every path releases every value exactly once, and you write nothing to make that happen. What is worth knowing is where on the path, because that is observable whenever the release runs a Drop body.

Every example on this page is compiled and executed by the compiler’s own test suite, and its heap is checked back to zero.

Where a release goes

Atoll places releases on the path, not at the end of a scope. There are five positions, and the second and third are the ones that surprise people:

The value is Released
forwarded or consumed — returned, stored, or passed to an owning parameter not here at all; whatever took it owes the release
never named again on the spot, right after the line that defined it
named later held to the end of the block
live on one arm of a branch, dead on the other on the arm that did not take it
never named at all, such as a call’s answer read for one field at the end of its statement

The fixture below makes the moment visible. Guard’s destructor writes through a cell the program can still read, so the answer is the ordering — no counter can see a Drop body run, because reference counting balances whether a body runs twice, once or never.

Never named again — released on the spot

An owning parameter the body never names is released on entry, since a parameter is defined at the call.

struct Cell { n int }

struct Guard {
    c ^Cell
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = 1 }
}

fn main() int {
    c := ^Cell { n: 0 }
    g := Guard { c: c }
    return c.^.n            // 1 — `g` is already gone
}

g looks like an RAII guard and is not one. Nothing below it mentions the name, so its destructor has already run by the time those lines execute.

The compiler says so. That shape is ATOLL4101:

warning[ATOLL4101]: `g` owes a destructor and is never used, so it is
released here rather than at the end of the block
  help: name `g` once after the region it guards: a value something later
  mentions is held to the end of the block, and one nothing mentions again
  is released on the spot. Renaming it `_g` silences this and changes
  nothing else.

Named later — held to the end of the block

One mention buys the whole block, not just the lines above it:

struct Cell { n int }

struct Guard {
    c ^Cell
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = 1 }
}

fn keep(g &Guard) int { return 0 }

fn main() int {
    c := ^Cell { n: 0 }
    g := Guard { c: c }
    keep(&g)                // the guard's last use…
    saw := c.^.n            // …and the cell still reads 0 here
    return saw
}

That is the repair ATOLL4101 asks for, and it is a repair rather than a restructuring: after one mention the value belongs to the block rather than to the line, so the region below the mention is covered too.

A condition is a mention like any other. The guard below is last named where the if tests it, and it still covers the arm the test chose:

struct Cell { n int }

struct Guard {
    c ^Cell
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = 1 }
}

fn main() int {
    c := ^Cell { n: 0 }
    g := Guard { c: c }
    mut saw := 5
    if g.c.^.n == 0 {       // the guard's last mention…
        saw = c.^.n         // …and the arm still reads 0
    }
    return saw
}

So is a match subject or guard, a loop condition, either side of && or ||, a for head, and a mention inside one arm. A name an arm’s pattern binds belongs to that arm, and is held to the arm’s end.

On the arm that did not take it

struct Cell { n int }

struct Guard {
    c ^Cell
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n + 1 }
}

fn consume(g Guard) int { return 0 }

fn main() int {
    c := ^Cell { n: 0 }
    mut total := 0
    mut i := 0
    for i < 2 {
        g := Guard { c: c }
        if i == 0 { consume(g) }
        total = total + c.^.n
        i += 1
    }
    return total
}

front-run=2 marks an answer the new compiler gives. Today’s compiler releases the guard where the arms meet and answers 3.

Read the arithmetic rather than the total. On the first pass consume takes the guard and runs the body inside itself, so the cell reads 1 and total becomes 1. On the second the if is not taken, so the guard is still held, and it is held to its brace as any value named later is: total reads the cell at 1 first, giving 2, and the guard is released at the end of the loop’s body.

A value handed on on some ways and not others is held, on the ways that kept it, to the end of the block it was made in, as Rust holds it. Where the ways cannot be told apart at the brace, the compiler keeps a flag. After the ways meet, the value is gone for use on all of them: naming it again is refused, as after a move.

  • A way that leaves the value’s block, a return, or a break or continue out of a loop the value was made in, releases what it still holds on its way out. The ways that go on hold the value to its brace, so a guard handed off on an early return still guards the rest of the block.
  • A break out of a loop the value was made outside of releases nothing at the loop’s exit. The ways that kept the value hold it to its brace.

Inside a loop, a read is the last on its way when every way on from it leaves the loop, whether it sits straight in the body or in an arm. One the loop goes round past is not, as the next turn reads the value again:

struct Cell { n int }

struct Guard {
    c  ^Cell
    id int
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 10 + self.id }
}

fn taken(c ^Cell, k int) int {
    q := ^Guard { c: c, id: 7 }
    for {
        if k < 37 {
            _q2 := q            // every way on from here leaves the loop:
        }                       // a move, `_q2` released on the spot; the
        break                   // other way holds `q` to its brace
    }
    return c.^.n                // 7 when taken; 0 when kept, `q` released after
}

fn round(c ^Cell) int {
    q := ^Guard { c: c, id: 7 }
    mut i := 0
    for i < 2 {
        i += 1
        if i > 5 {
            _q2 := q            // the loop goes round past it: a retain
        }
    }
    return c.^.n + 1            // 1: `q` is held to its brace
}

fn main() int {
    a := ^Cell { n: 0 }
    b := ^Cell { n: 0 }
    return taken(a, 1) * 100 + taken(b, 50) * 10 + round(^Cell { n: 0 })
}

front-run=701 marks an answer the new compiler gives: the Guard that taken hands on is released before the return reads the cell, and one it keeps is held to its brace. Today’s compiler answers 1.

A naive scheme leaks exactly here, releasing on neither edge or on both. In Atoll a value consumed on some incoming edges and not others is taken: it is held, on the ways that kept it, to its brace, and only a use of it after the ways meet is refused.

Never named — released at the end of its statement

A value no name holds, such as make() in make().id + c.n, is released at the end of the statement that made it, as Rust releases a temporary. The whole statement runs first, so c.n above reads the cell before the value’s Drop body runs. Two such values in one statement go in reverse of the order they were made, as owners at a brace go in reverse declaration order: mk(c, 1).id + mk(c, 2).id releases the second, then the first.

A temporary lent to a call, or to a method’s receiver, whose result may hold the loan is not released there: it lives as long as the name the statement binds, and goes with it. r := first(&make_str()) keeps the string as long as r, as t := make_str(); r := first(&t) would, and releases it with r, on the spot if r is never named again. The same holds where the value is a field of a struct or variant built there, or a block’s or arm’s tail. Rust refuses these programs (E0716). A call whose result holds no reference still ends its temporary at the statement.

fn first(s &string) &string { return s }

fn make_str() string { return "abcd" }

fn main() int {
    r := first(&make_str())     // the string lives as long as `r`
    return r.len()
}

Some parts of a statement end sooner, so a value made in one is released before what follows it runs:

  • the condition of an if, a while or a for, before the arm or the loop body, and an arm’s guard, before the arm’s body;
  • each arm’s body, and a block’s tail, before the block’s own owners;
  • each side of && or ||: the left side before the right side runs, and the right side, which runs only on some ways, before the operator’s answer is used. In if mk(c, 1).id > 0 && mk(c, 2).id > 0 { … } the first Guard goes before the second is made, as in Rust.
  • what the value a match or an if pattern := value reads makes, as soon as the arm that runs can no longer see it. This differs from Rust, which holds it through every arm to the end of the statement.

What the matched value makes is the value itself, where no name holds it, a value it is read from (the Pair in mk_pair(c).slot, the pointer in mk_ptr(c).slot), and any other value made in it whose release runs a Drop body. An arm that binds nothing that refers into the value, such as _, a bare variant, a payload copied (an int), or the else of an if pattern := value, releases it before its body runs. Any other arm holds it through its body and releases it at its end, before the rest of the statement, in reverse of the order made. In match open_guard().kind { Kind.Read => read_all(), Kind.Write => write_all() } the guard goes before either arm’s call runs, because neither arm sees it; Rust would hold it, a lock among them, through the call. In if Made.Yes(g) := mk(c, k) { mark(c, g.id) } else { mark(c, 6) } the Made.Yes goes after mark(c, g.id) and a Made.No goes before mark(c, 6). A match on a named local is not one of these: the local keeps its value to its own end. What the iterated expression of a for … in makes is held through the whole loop.

The left side of && and of || is released before the right side runs:

struct Cell { n int }

struct Guard {
    c  ^Cell
    id int
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 10 + self.id }
}

fn mk(c ^Cell, id int) Guard { return Guard { c: c, id: id } }

fn note(c ^Cell, k int) void {
    mut w := c
    w.^.n = w.^.n * 10 + k
}

fn mark(c ^Cell, k int) bool {
    note(c, k)
    return true
}

fn and_left(c ^Cell) void {
    if mk(c, 1).id > 0 && mark(c, 5) {
        note(c, 9)                  // 1, then 5: the left side went first
    }
}

fn or_left(c ^Cell) void {
    if mk(c, 2).id < 0 || mark(c, 6) {
        note(c, 8)                  // 2, then 6
    }
}

fn main() int {
    c := ^Cell { n: 0 }
    and_left(c)
    or_left(c)
    return c.^.n                    // 159268
}

A block whose answer is not kept, such as a void function’s body, a loop’s body, a block written as a statement, or an arm of an if or match written as a statement, ends its last line as a statement: { a := mk(c, 1); mk(c, 2) } there is { a := mk(c, 1); mk(c, 2); }, so the second Guard goes before the block’s defers and before a:

struct Cell { n int }

struct Guard {
    c  ^Cell
    id int
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 10 + self.id }
}

fn mk(c ^Cell, id int) Guard { return Guard { c: c, id: id } }

fn note(c ^Cell, k int) void {
    mut w := c
    w.^.n = w.^.n * 10 + k
}

fn block(c ^Cell) void {
    {
        a := mk(c, 1)
        defer note(c, a.id + 2)
        mk(c, 2)                    // a statement: released first
    }
}

fn body(c ^Cell) void {
    a := mk(c, 4)
    defer note(c, a.id + 1)
    mk(c, 6)
}

fn main() int {
    c := ^Cell { n: 0 }
    block(c)
    body(c)
    return c.^.n                    // 231, then 654
}

A return, a break or a ? part way through a statement releases what the statement has made so far. A value made as an operand of a call, a literal or a constructor that never runs belongs to the innermost of these scopes that holds the call, and is a scope of its own only where that scope ends past the call, as a statement’s does; the way out releases it with that scope’s values in reverse of the order made. So if mix(mk(c, 1), &mk(c, 2), mk(c, 3), { return 10 }) { … } releases 3, 2, then 1, while the statement mix(mk(c, 1), &mk(c, 2), mk(c, 3), { return 10 }) releases the call’s operands, 3 and 1, before the statement’s 2, as Rust does. An arm’s body keeps its call’s operands apart as a statement does. Where nothing can see the moment, because the value has no Drop body and holds none, the compiler may release it sooner.

Today’s compiler still releases such a value at the end of its function or loop turn; the new compiler follows the rule above.

struct Cell { n int }

enum Pick { Take, Keep }

struct Guard {
    c  ^Cell
    id int
    p  Pick
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 2 + self.id }
}

fn make(c ^Cell, p Pick) Guard { return Guard { c: c, id: 7, p: p } }

fn expression() int {
    c := ^Cell { n: 1 }
    t := make(c, Pick.Keep).id + c.^.n   // 7 + 1: the whole statement first
    return t * 100 + c.^.n                // then the release: 800 + 9
}

fn condition() int {
    c := ^Cell { n: 1 }
    if make(c, Pick.Keep).id > c.^.n {
        return c.^.n                      // 9: released before the arm
    }
    return 0
}

fn scrutinee() int {
    c := ^Cell { n: 1 }
    return match make(c, Pick.Take).p {
        Take => c.^.n                     // 9: the arm sees none of it
        Keep => 0
    }
}

fn arm(p Pick) int {
    c := ^Cell { n: 1 }
    t := (match p {
        Take => make(c, Pick.Keep).id * 10 + c.^.n   // 71, then released
        Keep => 0
    }) * 100 + c.^.n                      // 7100 + 9
    return t
}

fn early(c ^Cell, p Pick) int {
    t := make(c, Pick.Keep).id + match p {
        Take => return c.^.n * 1000       // 1000, then released on the way out
        Keep => 1
    }
    return t
}

fn way_out() int {
    c := ^Cell { n: 1 }
    r := early(c, Pick.Take)
    return r + c.^.n                      // 1000 + 9
}

fn broken(p Pick) int {
    c := ^Cell { n: 1 }
    mut i := 0
    for i < 3 {
        i += make(c, Pick.Keep).id + match p {
            Take => break                 // released on the way out
            Keep => 1
        }
    }
    return i * 100 + c.^.n                // 0 + 9
}

fn main() int {
    a := expression() * 10000 + arm(Pick.Take)
    b := a * 10000 + way_out()
    return b * 1000 + condition() * 100 + scrutinee() * 10 + broken(Pick.Take)
}

front-run=80971091009999 marks an answer the new compiler gives: each value is released where the rule says. Today’s releases each at the end of its function or loop turn, and answers 80171019009199.

A return among a call’s operands, in a statement and in a condition:

struct Cell { n int }

struct Guard {
    c  ^Cell
    id int
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 10 + self.id }
}

fn mk(c ^Cell, id int) Guard { return Guard { c: c, id: id } }

fn mix(a Guard, b &Guard, d Guard, k int) bool { return a.id + b.id + d.id + k > 0 }

fn statement(c ^Cell) int {
    mix(mk(c, 1), &mk(c, 2), mk(c, 3), { return 10 })
    return 0
}

fn condition(c ^Cell) int {
    if mix(mk(c, 1), &mk(c, 2), mk(c, 3), { return 20 }) {
        return 1
    }
    return 0
}

fn main() int {
    c := ^Cell { n: 0 }
    s := statement(c)               // 10: 3, 1, then the statement's 2
    t := condition(c)               // 20: 3, 2, 1
    return (s + t / 10) * 1000000 + c.^.n
}

front-run=12312321 marks an answer the new compiler gives. Today’s compiler releases the three in the order made in both, and answers 12123123.

Two values made in one statement, and one made on the right side of &&:

struct Cell { n int }

struct Guard {
    c  ^Cell
    id int
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 2 + self.id }
}

fn mk(c ^Cell, id int) Guard { return Guard { c: c, id: id } }

fn two() int {
    c := ^Cell { n: 0 }
    t := mk(c, 1).id + mk(c, 2).id + c.^.n   // 3, then 2 released, then 1
    return t * 10 + c.^.n                      // 30 + (0 * 2 + 2) * 2 + 1
}

fn lazy() int {
    c := ^Cell { n: 0 }
    mut i := 0
    mut t := 0
    for i < 2 && mk(c, 1).id > 0 {             // released before the body
        i += 1
        t = t * 10 + c.^.n                     // 1, then 13
    }
    return t * 10 + c.^.n                      // 130 + 3
}

fn main() int {
    return two() * 1000 + lazy()
}

two releases the second Guard, then the first, after the whole statement has read the cell; lazy releases what its condition made before each turn of the loop’s body. Today’s compiler answers 30133.

What a match reads makes is released as soon as the arm that runs can no longer see it, and so is any value made in the scrutinee, or one it is read from. A payload an arm binds is read in place; it goes with the whole value at the end of that arm, unless the arm moves it:

struct Cell { n int }

struct Guard {
    c  ^Cell
    id int
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 10 + self.id }
}

enum Slot {
    Held(Guard)
    Empty
}

struct Pair {
    tag  Guard
    slot Slot
}

fn mk(c ^Cell, id int) Guard { return Guard { c: c, id: id } }

fn mk_slot(c ^Cell, id int) Slot { return Slot.Held(Guard { c: c, id: id }) }

fn mk_pair(c ^Cell) Pair { return Pair { tag: mk(c, 3), slot: mk_slot(c, 5) } }

fn wild() int {
    c := ^Cell { n: 0 }
    mut t := 0
    match mk_slot(c, 5) {
        Held(_) => t = c.^.n + 1        // released before the arm: 5 + 1
        Empty => t = 9
    }
    return c.^.n * 100 + t              // 506
}

fn bound() int {
    c := ^Cell { n: 0 }
    mut t := 0
    match mk_slot(c, 5) {
        Held(g) => t = g.id + c.^.n     // `g` reads in place: 5 + 0, then released
        Empty => t = 9
    }
    return c.^.n * 100 + t              // 505
}

fn field_wild() int {
    c := ^Cell { n: 0 }
    mut t := 0
    match mk_pair(c).slot {
        Held(_) => t = c.^.n + 1        // the pair first, tag then slot: 35 + 1
        Empty => t = 9
    }
    return c.^.n * 100 + t              // 3536
}

fn field_bound() int {
    c := ^Cell { n: 0 }
    mut t := 0
    match mk_pair(c).slot {
        Held(g) => t = g.id + c.^.n     // `g` reads in place: 5 + 0; the pair goes after the arm
        Empty => t = 9
    }
    return c.^.n * 100 + t              // 3505
}

fn inside() int {
    c := ^Cell { n: 0 }
    mut t := 0
    match mk_slot(c, mk(c, 1).id) {     // `mk(c, 1)` is held through the arm that sees the slot
        Held(g) => t = g.id * 10 + c.^.n    // 10 + 0
        Empty => t = 9
    }
    // at the arm's end the slot, made last, goes first, then `mk(c, 1)`: 11
    return c.^.n * 100 + t              // 1110
}

fn main() int {
    a := wild() * 1000 + bound()
    b := field_wild() * 10000 + field_bound()
    return (a * 100000000 + b) * 10000 + inside()
}

Today’s compiler holds each to the end of the function and answers 1505000135051111.

A pointer made there is such a value, and its count is released the same way. Where another name holds the pointer, only the count falls:

struct Cell { n int }

struct Guard {
    c  ^Cell
    id int
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 10 + self.id }
}

enum Slot {
    Held(Guard)
    Empty
}

struct Pair {
    tag  Guard
    slot Slot
}

fn mk(c ^Cell, id int) Guard { return Guard { c: c, id: id } }

fn mk_slot(c ^Cell, id int) Slot { return Slot.Held(Guard { c: c, id: id }) }

fn mk_ptr(c ^Cell) ^Pair { return ^Pair { tag: mk(c, 3), slot: mk_slot(c, 5) } }

fn again(p ^Pair) ^Pair { return p }

fn ptr_wild() int {
    c := ^Cell { n: 0 }
    mut t := 0
    match mk_ptr(c).slot {
        Held(_) => t = c.^.n + 1        // the pair first, tag then slot: 35 + 1
        Empty => t = 9
    }
    return c.^.n * 100 + t              // 3536
}

fn ptr_kept() int {
    c := ^Cell { n: 0 }
    p := mk_ptr(c)
    mut t := 0
    match again(p).slot {
        Held(_) => t = c.^.n + 1        // a count falls, `p` still holds: 0 + 1
        Empty => t = 9
    }
    t = t * 10 + c.^.n                  // 10
    return t + p.tag.id * 0             // `p` is released at its brace
}

fn main() int {
    return ptr_wild() * 100 + ptr_kept()
}

Today’s compiler answers 110.

A brace is a boundary

A held value is released at the end of the block that holds it, and a bare { } is a block. So a guard put inside braces is released at the closing one:

struct Cell { n int }

struct Guard {
    c ^Cell
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n + 1 }
}

fn keep(g &Guard) int { return 0 }

fn main() int {
    c := ^Cell { n: 0 }
    {
        g := Guard { c: c }
        keep(&g)
    }
    return c.^.n            // 1 — the brace ended the block
}

This page said the opposite, and it was measured: an if arm and a loop body got their boundary from being CFG blocks already, and a bare { } was lowered in place — so its guard was released at the end of the enclosing function. Safe, since holding longer is never wrong, and unpredictable in the one construct a programmer reaches for to bound a resource.

A function still bounds one too, and is the right tool when the region has a name:

struct Cell { n int }

struct Guard {
    c ^Cell
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n + 1 }
}

fn keep(g &Guard) int { return 0 }

fn region(c ^Cell) int {
    g := Guard { c: c }
    return keep(&g)
}

fn main() int {
    c := ^Cell { n: 0 }
    region(c)
    return c.^.n            // 1 — the callee's frame ended
}

defer reaches the same brace. A brace undoes its block in reverse, as Rust does: values in reverse of the order they were declared, and each defer in its place among them, so a defer runs before the values declared ahead of it are released and after those declared behind it:

struct Cell { n int }

fn main() int {
    mut c := ^Cell { n: 0 }
    {
        defer c.^.n = c.^.n * 10
        c.^.n = 4
    }
    c.^.n = c.^.n + 1
    return c.^.n            // 4 → 40 at the brace, then 41
}

An exit that leaves several braces at once leaves them one by one, innermost first, and each brace undoes its own block in reverse.

struct Cell { n int }

struct Guard {
    c  ^Cell
    id int
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 10 + self.id }
}

fn leave(c ^Cell) int {
    mut k := c
    outer := Guard { c: k, id: 4 }
    defer k.^.n = k.^.n * 10 + 3
    {
        inner := Guard { c: k, id: 2 }
        defer k.^.n = k.^.n * 10 + 1
        return inner.id + outer.id
    }
}

fn main() int {
    c := ^Cell { n: 0 }
    leave(c)
    return c.^.n            // 1234: the inner brace's defer and release, then the outer's
}
struct Cell { n int }

struct Guard {
    c  ^Cell
    id int
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 10 + self.id }
}

fn unwind(c ^Cell) int {
    mut k := c
    a := Guard { c: k, id: 1 }
    defer k.^.n = k.^.n * 10 + 2
    b := Guard { c: k, id: 3 }
    d := Guard { c: k, id: 4 }
    return a.id + b.id + d.id
}

fn main() int {
    c := ^Cell { n: 0 }
    unwind(c)
    return c.^.n            // 4321: `d`, then `b`, then the defer, then `a`
}

front-run=4321 marks an answer the new compiler gives. Today’s compiler runs the defer first and releases in declaration order, and answers 2134.

A function’s own brace undoes its locals before its parameters, and its parameters in reverse of their order:

struct Cell { n int }

struct Guard {
    c  ^Cell
    id int
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 10 + self.id }
}

fn ignore(g Guard, c ^Cell) int {
    return c.^.n            // 4: `g` went on entry
}

fn order(a Guard, b Guard, c ^Cell) int {
    d := Guard { c: c, id: 3 }
    return a.id + b.id + d.id
}

fn main() int {
    c := ^Cell { n: 0 }
    seen := ignore(Guard { c: c, id: 4 }, c)
    order(Guard { c: c, id: 1 }, Guard { c: c, id: 2 }, c)
    return seen * 10000 + c.^.n     // 4, then 4321: `d`, then `b`, then `a`
}

front-run=44321 marks an answer the new compiler gives. Today’s compiler releases an unnamed parameter at the end of the call and the rest in declaration order, and answers 4123.

A local moved away and filled again keeps its place in that order: it is released where it was declared, not where it was filled:

struct Cell { n int }

struct Guard {
    c  ^Cell
    id int
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 10 + self.id }
}

fn mk(c ^Cell, id int) Guard { return Guard { c: c, id: id } }

fn consume(g Guard) void { }

fn refill(c ^Cell) int {
    mut a := mk(c, 1)
    b := mk(c, 2)
    consume(a)                      // 1
    a = mk(c, 3)
    return a.id + b.id              // `b`, then `a`: declared first, released last
}

fn main() int {
    c := ^Cell { n: 0 }
    refill(c)
    return c.^.n                    // 123
}

front-run=123 marks an answer the new compiler gives. Today’s compiler refuses the program (ATOLL5301).

Use defer when the moment matters and Drop when the type owes the cleanup. See Defer.

What a release does

Freeing a block may mean walking it first, and the shape of that walk is decided by the type — never by a runtime scan of the bytes:

The type holds The release
nothing that owns anything frees the block whole
a fixed set of owning fields releases each one, at offsets known at compile time
a tagged value releases what the discriminant says is live
a Drop impl runs the body, then walks whatever is left
a collection runs len element releases, because len is a value and no offset list can say it

The fourth row is the general mechanism rather than a special case — the classifier keys on exactly one thing, whether the type declares Drop — and the fifth is not that row. List declares no Drop; its element walk is a plan of its own, a loop over len, and the compiler carries a guard that fails if a Drop ever appears on it, because a body running beside that walk would release each element twice. Map is the collection that does declare one, for a different reason: its table is three regions no element stride describes, so the walk is written out in stdlib/map.at.

The walk takes the elements in order, the first first, each released as its own type says, a Drop body before its fields:

struct C { n int }

struct Bump {
    c ^C
    k int
}

impl Drop for Bump {
    fn drop(&mut self) void {
        self.c.^.n = self.c.^.n * 10 + self.k
    }
}

fn fill(c ^C) int {
    bumps := [Bump { c: c, k: 1 }, Bump { c: c, k: 2 }, Bump { c: c, k: 3 }]
    return bumps.len()   // the list's last release: 1, then 2, then 3
}

fn main() int {
    c := ^C { n: 0 }
    n := fill(c)
    return n * 1000 + c.^.n    // 3123
}

A tagged value’s walk reads its tag first, and a variant that holds nothing releases nothing. A match reads a payload where it is, without taking it, so the guard below is released once, when held is, at the brace:

struct Cell { n int }

struct Guard {
    c  ^Cell
    id int
}

impl Drop for Guard {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 10 + self.id }
}

enum Slot {
    Held(Guard)
    Empty
}

fn main() int {
    c := ^Cell { n: 0 }
    mut seen := 0
    {
        held := Slot.Held(Guard { c: c, id: 1 })
        empty := Slot.Empty
        a := match held { Held(g) => g.id * 10 Empty => 0 }
        b := match empty { Held(g) => g.id Empty => 2 }
        seen = a + b
    }
    return c.^.n * 100 + seen  // 112: one guard released, once
}

Drop

Drop is for resource semantics — closing a handle, releasing a lease, committing a buffer. Memory is already handled, so a Drop body that only frees memory has nothing to do.

@host fn record(n int) void

struct Handle { id int }

impl Drop for Handle {
    fn drop(&self) void { record(self.id) }
}

fn main() int {
    h: Handle = Handle { id: 7 }
    record(1)
    return h.id              // records 1, then 7 as `h` is destroyed
}

The records=1,7 is checked: this book asserts the call log, not only the answer, because a Drop body that never runs and one that runs twice leave the answer and the heap identical.

The body, then the fields

A value’s Drop body runs first, while every field is still whole. Then its fields are released in the order they are declared, each the same way: a field whose type has a Drop runs that body, then releases its own fields.

@host fn record(n int) void

struct Tag { n int }

impl Drop for Tag {
    fn drop(&self) void { record(self.n) }
}

struct Pair {
    first  Tag
    second Tag
}

impl Drop for Pair {
    fn drop(&self) void { record(9) }
}

fn main() int {
    p := Pair { first: Tag { n: 1 }, second: Tag { n: 2 } }
    return 0                 // records 9, then 1, then 2 as `p` is destroyed
}

A field that is a ^T is released in its place in that order too, with the fields held inline around it. Its count is what is released there, and the pointee’s body runs when that count was the last:

struct Cell { n int }

struct Tag {
    c  ^Cell
    id int
}

impl Drop for Tag {
    fn drop(&mut self) void { self.c.^.n = self.c.^.n * 10 + self.id }
}

struct Three {
    first  ^Tag
    second Tag
    third  ^Tag
}

fn main() int {
    c := ^Cell { n: 0 }
    {
        _t := Three {
            first: ^Tag { c: c, id: 1 },
            second: Tag { c: c, id: 2 },
            third: ^Tag { c: c, id: 3 }
        }
    }
    return c.^.n            // 123: first, second, third
}

front-run=123 marks an answer the new compiler gives: today’s releases the inline field before the pointers either side of it, and answers 132.

Two shapes are refused

An enum cannot carry a Drop body. A layout can say run this body, then walk these offsets or which references are live depends on the tag — not both:

enum Shape {
    Dot
    Line { n: int }
}

impl Drop for Shape {
    fn drop(&self) void { }
}

fn main() int {
    s: Shape = Shape.Dot
    return match s { Dot => 1 Line { n } => n }
}

The refusal names the repair: wrap it in a one-shape struct and put the Drop there. A distinct alias over a pointer or a handle is refused for the same reason — folding a body over one of those would empty the lane every containment check reads.

A value that owes a destructor has no second name

A type with a Drop impl cannot be duplicated: there is no correct number of times to run a body. So it moves as a List does, on a second name and into a parameter that owns it, with no clone() available to escape, unless you write one.

struct Handle { id int }

impl Drop for Handle {
    fn drop(&self) void { }
}

fn consume(h Handle) int { return h.id }

fn main() int {
    h: Handle = Handle { id: 7 }
    consume(h)
    return h.id            // ATOLL3102 — `h` was consumed
}

The way to use one twice is a single name and a borrow: fn look(h &Handle).

Nor is one taken apart. Its drop reads every field, so a type with a Drop of its own is never partly moved: a move out of its field would leave the body reading a field already taken, and is refused (ATOLL1117), as Rust refuses it. .clone() spells the copy where there is one, and a &T parameter reads the field where it is.

struct Label { name string, other string }

impl Drop for Label {
    fn drop(&mut self) void { }
}

fn main() int {
    l := Label { name: "ab", other: "cde" }
    s := l.name             // refused: `drop` would read `l.name` after this
    return s.len()
}

front-fail=ATOLL1117 marks a refusal the new compiler gives. Today’s compiler takes the move and runs drop over a value whose field is gone.

A borrow gives no second name either. Reading a Drop value by value through one, return r.^ or eat(r.^) with r &Handle, would copy it, and is refused:

struct Handle { id int }

impl Drop for Handle {
    fn drop(&mut self) void { }
}

fn steal(r &Handle) Handle {
    return r.^              // refused: a second `Handle`, copied out of a borrow
}

Today’s compiler takes such a read when the type’s fields are all numbers, as a copy of the bits that it never releases.

A Drop body is never called by name

A value’s drop runs once, where the value ends, so the program never calls it: g.drop() would run the body over a value still in use, and again where g ends. A call that reaches a type’s Drop body is refused (ATOLL1141), as Rust refuses it, in every spelling: on the value, through a borrow or a ^T, and as Guard.drop(&mut g) or Drop.drop(&mut g). A method named drop that is not the Drop body, an inherent one or the stdlib’s string.drop, is called as any other.

struct Guard { id int }

impl Drop for Guard {
    fn drop(&mut self) void { println("drop ${self.id}") }
}

fn main() {
    mut g := Guard { id: 1 }
    g.drop()                // refused: `drop` would run again where `g` ends
    println("after")
}

To end a value sooner, hold it in a block of its own ({ ... }): its drop runs at the block’s closing brace. Today’s compiler takes the call and runs the body twice.

Every exit releases

The placement above is per path, and every path counts — an early return, a break, a ? that propagates an error, and a task that is cancelled while suspended. A suspending call has two exits, a resume edge and a cancel edge, and both carry the same live values, so the releases land on the cancelled path from the same rule. A cancelled path that releases nothing is a compiler error rather than a leak nothing looks for.

The one asymmetry is the call’s own result: it exists only on the resume edge, because a cancelled call produced none.

spawn is the same question with no answer at all, which is why a spawned task may not be handed a reference into the spawning frame — there is no edge left to release it on. See Cancellation.

  • References — a ^T keeps its block alive, so where one may travel is the other half of this rule.
  • Cycles — what reference counting cannot reclaim.
  • Ownership — counts, walks and reuse underneath.

Type to search…

↑↓ navigate↵ selectEsc close