🦀 Rust
Destructor / Finally

Updated at 2024-02-24 04:23

Rust doesn't have an official destructor or finally keyword, but it does have the Drop trait. The Drop trait is used to run code when a value goes out of scope.

Useful, but don't rely on it too much, like any finally block.

It is not guaranteed that the Drop will run.

  • if a panicking thread panics again; e.g., in another destructor
  • if running in -C panic=abort mode, no unwinding is done
  • out of memory error leading to abort
  • infinite loop exited with an abort
  • power failure, etc.
struct FooFinally;

impl Drop for FooFinally {
    fn drop(&mut self) {
        println!("ah, finally!");

fn bar() -> Result<(), ()> {
    let _finally = FooFinally;