#defer #deferred #go

no-std defer-lite

A lightweight high-performance implementation of Go's defer statement

1 stable release

1.0.0 Aug 10, 2021

#656 in Rust patterns

Download history 4024/week @ 2022-12-05 2397/week @ 2022-12-12 3729/week @ 2022-12-19 1719/week @ 2022-12-26 2488/week @ 2023-01-02 990/week @ 2023-01-09 4351/week @ 2023-01-16 2980/week @ 2023-01-23 1760/week @ 2023-01-30 2337/week @ 2023-02-06 3125/week @ 2023-02-13 1889/week @ 2023-02-20 3260/week @ 2023-02-27 2509/week @ 2023-03-06 3088/week @ 2023-03-13 1433/week @ 2023-03-20

10,520 downloads per month
Used in 5 crates (3 directly)

MIT license

5KB

defer-lite

Crates.io Docs.rs License: MIT

A Rust implementation of Go's defer statement as the defer! macro, which executes a block of code when the surrounding scope ends.

This crate focuses on providing a lightweight, high-performance, no_std implementation of the defer! macro.

Usage

Add the dependency in your Cargo.toml:

[dependencies]
defer-lite = "1.0.0"

Examples

Simplest example:

use defer_lite::defer; // import the defer! macro

fn main() {
    defer! { println!("Second"); }
    println!("First");
}

Multiple statements:

use defer_lite::defer;

fn main() {
    defer! {
        println!("Second");
        println!("Third");
    }
    println!("First");
}

In Go, the defer code runs when the function exits. In this Rust implementation, the code runs when the surrounding scope ends – this makes it possible to use defer inside loops:

use defer_lite::defer;

fn main() {
    defer! { println!("End"); }
    println!("Before");

    for i in 0..2 {
        defer! { println!("Defer {}", i); }
        println!("Loop {}", i);
    }

    println!("After");
}

License

Licensed under MIT license, see LICENSE.md for details.

No runtime deps