Destructors
A destructor is code the compiler runs when a value's life ends. It is declared in an extend block, named after its type with a leading ~, and it borrows the dying value mutably. Nothing calls it by name: the compiler invokes it exactly once for each initialized value that still owns its state, and never for a value that was moved away or never initialized.
Syntax
extend T {
func ~T(&var self) { … }
}
struct Guest {
name: char8[..];
}
extend Guest {
func ~Guest(&var self) {
PrintLine("{} leaves", self.name);
}
}
The shape is fixed: one receiver, &var self, no other parameters, no result, no type parameters, and a body. For a generic type the name carries no type arguments: func ~Store(&var self) inside extend Store<T>. A destructor cannot be unsafe, because nothing marks where it is called, and no error may leave it, so a call in it that can throw is written try? or try ... catch.
| Mistake | Error |
|---|---|
func ~Guest(&self) | destructor for type 'Guest' must have signature 'func ~Guest(&var self)' |
func ~Visitor(&var self) in extend Host | destructor '~Visitor' must be named '~Host' for type 'Host' |
func ~Ghost(&var self); | destructor '~Ghost' must have a body |
a destructor outside extend | destructor '~Item' may only be declared in an extend block |
seat.~Guest(); | expected a field name or tuple index after '.' before '~' |
A destructor cannot be called. To end a value's life early, replace it or move it into a function that lets it go.
When destruction runs
| Event | What is destroyed |
|---|---|
| The owning scope ends — a block, a function, each pass of a loop body | every value it still owns |
return, break, continue, ? propagation | the values of every scope being left |
| An error leaving a scope for its handler or the caller | the values of every scope being left |
= into a live place | the old value, after the new one is produced |
A destructuring let, or a match or catch arm that owns its subject | each part bound to _ or left out of the pattern |
let _ = move value; | the value, at the statement |
| A by-value parameter | the parameter, when the function returns |
| Not destroyed | Why |
|---|---|
A value moved away with move | its new owner destroys it |
A value returned with return move value; | the caller owns it now |
| Storage declared without a value and never assigned | it holds nothing |
| The old contents of storage written through a raw pointer | a pointer cannot tell whether the storage holds a value |
| Anything, when the program panics or exits | panics do not unwind |
A write through a raw pointer — *p = move value, p[i] = value, or a field reached through *var T — initializes the storage it addresses and destroys nothing. Code that replaces a value through a pointer destroys or moves out the old one first.
Order
Values that end together are destroyed in reverse order of creation, newest first: a value made later may depend on one made earlier, so it has to go while the earlier one is still there.
A value's own destructor runs first, while its fields are still intact. Then the compiler destroys its contents — fields, tuple and array elements, and the payload of a variant case or optional — in reverse construction order: the last field first, the last element first.
struct Part {
name: char8[..];
}
extend Part {
func ~Part(&var self) {
PrintLine("~Part {}", self.name);
}
}
struct Machine {
first: Part;
second: Part;
}
extend Machine {
func ~Machine(&var self) {
PrintLine("~Machine");
}
}
func Build() {
let machine = Machine { first: Part { name: "first" }, second: Part { name: "second" } };
let a = Part { name: "a" };
let b = Part { name: "b" };
}
Build prints ~Part b, ~Part a, ~Machine, ~Part second, ~Part first.
A type with no destructor of its own still has its droppable parts destroyed: the compiler generates that cleanup for every structure, tuple, array, variant and optional that contains something to destroy.
Replacement
Assigning to a place that holds a value replaces it in three steps: the new value is produced — a copy, a move, or a Clone call — then the old value is destroyed, then the new one is installed. A field, a tuple element and an element of an array or slice are places like any other, whether they belong to a local or are reached through a &var reference:
var seat = Guest { name: "Bob" };
seat = Guest { name: "Cy" }; // Bob leaves here
A part of a local holds a value only while the local holds one. A droppable local declared without a value, or moved from, is assigned whole before any part of it is written, because a part written into empty storage would never be destroyed:
error: cannot write field 'guest' of 'table', which holds no value
note: 'table' was declared without a value at …
note: 'Table' needs destruction, and a value written into a part of storage that holds none would never be destroyed
help: initialize 'table' whole, as in 'table = Table { ... }'
A type with nothing to destroy may still be filled one part at a time; see Initialization.
Drop flags
Whether a local still owns its value can depend on the path taken. When a value is moved on only some paths, the compiler keeps a drop flag for it, and the flag — not the source text — decides at the end of the scope whether the value is destroyed:
func Visit(away: bool) {
let guest = Guest { name: "Dee" };
if away {
let taken = move guest; // destroyed here, as 'taken'
return;
}
} // destroyed here only when not moved
Either way Dee leaves is printed once. A local's flag covers the whole value, which is why a part cannot be moved out on its own.
Destructors make a type move-only
A type that declares a destructor owns resources, so it is never copied implicitly: copying its bytes would leave two owners to release the same memory or close the same file. Such a type, and anything holding one, is move-only, and each value is destroyed by its last owner. A named value of it is transferred with move, and duplicated only by a method such as Clone that duplicates the resource; see Copy and move.
Destructuring
A destructure that takes its value over owns every part of it: a destructuring let, and a match arm whose subject was handed over with move, is a temporary, or is the copy a by-value match makes of plain data, as well as a catch arm, which owns the error. A part bound to a name belongs to that binding. A part bound to _, and a structure field the pattern leaves out, has no owner left, so it is destroyed on the spot — at the let, or at the top of the arm before its body runs — in the order the parts appear in the pattern:
let (_, second) = move pair; // the first element is destroyed here
let _ = move guest; // 'guest' is destroyed here
An arm that binds nothing from a consumed subject destroys it whole, and a consumed subject no arm takes is destroyed as the match ends. A structure that declares ~T cannot be split by a moving pattern, because its destructor runs on the whole value; it can still be tested with a pattern that binds none of its fields, bound whole, or matched through a borrow:
error: cannot split 'Handle' with a moving pattern, because it declares destructor '~Handle'
No unwinding
A panic stops the program where it happens. Nothing is unwound: no destructor runs and no deferred statement runs, in the panicking function or in any caller. The same holds for ending the process. Cleanup that must survive a failure belongs on an error path — an error leaving through throw or try does run destructors.
See also
- Defer — cleanup tied to a scope, and how it is ordered against destructors
- Copy and move — move-only types and
Clone - Extensions — the
extendblock a destructor lives in - Panics — failures that end the program without cleanup
- Learn: Destructor
Copy and Move
Plain data copies and every other type moves. Clone duplicates an owning value, #NoCopy and #NoMove take a capability away, and neither operation ever runs user code.
Defer
defer registers one statement to run when the enclosing scope ends — last registered, first run, after the return value or the error is captured.