https://github.com/rodrigocfd/defer-lite
A lightweight high-performance implementation of Go's defer statement.
https://github.com/rodrigocfd/defer-lite
defer rust
Last synced: about 1 year ago
JSON representation
A lightweight high-performance implementation of Go's defer statement.
- Host: GitHub
- URL: https://github.com/rodrigocfd/defer-lite
- Owner: rodrigocfd
- License: mit
- Created: 2021-08-10T01:33:37.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2021-08-10T01:58:44.000Z (almost 5 years ago)
- Last Synced: 2025-03-24T19:21:42.752Z (over 1 year ago)
- Topics: defer, rust
- Language: Rust
- Homepage: https://crates.io/crates/defer-lite
- Size: 3.91 KB
- Stars: 23
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# defer-lite
[](https://crates.io/crates/defer-lite)
[](https://docs.rs/defer-lite)
[](https://opensource.org/licenses/MIT)
A Rust implementation of [Go's `defer` statement](https://tour.golang.org/flowcontrol/12) 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`:
```toml
[dependencies]
defer-lite = "1.0.0"
```
## Examples
Simplest example:
```rust
use defer_lite::defer; // import the defer! macro
fn main() {
defer! { println!("Second"); }
println!("First");
}
```
Multiple statements:
```rust
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:
```rust
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](https://opensource.org/licenses/MIT), see [LICENSE.md](LICENSE.md) for details.