Drop
A struct can run code when it goes away by implementing the prelude trait
Drop:
import fs
struct TempDir { path: Str}
impl Drop for TempDir { fn drop(&mut self) { fs.remove(&self.path) catch {} }}
let _scratch = TempDir { path: "/tmp/brass-scratch-example" }drop runs exactly once, when the value goes away: at the end of its
scope (in reverse order of declaration), when it is overwritten, when the
temporary holding it is freed, or when the collection or struct holding it
is dropped; then its fields are freed. A moved value runs nothing where it
was moved from. The rules keep that “exactly once” true:
dropcannot be called by hand (x.drop()andDrop.drop(&mut x)are errors); end the scope or move the value instead.- A value holding something with a
dropcannot be cloned, since the cleanup would then run twice. - Fields cannot be moved out of it, by assignment or by a pattern; match on a reference instead, or clone the field.
- Such a type is never Copy, and
droptakes&mut selfand cannot fail. - Structs and enums (generic ones too) can implement
Drop: each carries a hidden “alive” mark that moving clears. - A variable whose dropping runs a
dropis never reported as unused, so guards likelet _lock = acquire()need nothing extra.