#go #deferred #defer

no-std defer-lite

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

1 stable release

1.0.0 Aug 10, 2021

#999 in Rust patterns

Download history 653/week @ 2024-12-09 622/week @ 2024-12-16 429/week @ 2024-12-23 348/week @ 2024-12-30 577/week @ 2025-01-06 497/week @ 2025-01-13 517/week @ 2025-01-20 79/week @ 2025-01-27 366/week @ 2025-02-03 453/week @ 2025-02-10 568/week @ 2025-02-17 562/week @ 2025-02-24 389/week @ 2025-03-03 368/week @ 2025-03-10 421/week @ 2025-03-17 461/week @ 2025-03-24

1,669 downloads per month
Used in 19 crates (13 directly)

MIT license

6KB

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