Skip to content

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:

  • drop cannot be called by hand (x.drop() and Drop.drop(&mut x) are errors); end the scope or move the value instead.
  • A value holding something with a drop cannot 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 drop takes &mut self and 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 drop is never reported as unused, so guards like let _lock = acquire() need nothing extra.