#defer #raii #macro

macro defr

Golang defer statements but in Rust

1 unstable release

0.1.0 Nov 20, 2022

#17 in #raii

MIT license

4KB

defr

Golang defer statements but in Rust.

Overview

A simple library that provides a convenient macro for wrapping expressions with the drop method.

What is defer?

The meaning might vary but in the Golang context, defer is the finalizer. Unlike C++ and Rust, Golang does not have destructor equivalents. More on defer statements.

Difference

defer calls in Golang are pushed onto a stack, then run in a last-in-first-out manner.

func main() {
    defer run_4th()
    defer run_3rd()
    run_1st()
    run_2nd()
}

The expressions inside defr! block remain procedural.

fn main() {
    defr! {
        run_3rd();
        run_4th();
    }
    run_1st();
    run_2nd();
}

Notes

Definitely not a replacement for implementing the Drop trait. In fact, in most cases, the RAII pattern is the way.

Dependencies

~1.5MB
~37K SLoC