| Crates.io | irgo |
| lib.rs | irgo |
| version | 0.2.0 |
| created_at | 2025-04-15 06:50:46.960653+00 |
| updated_at | 2025-04-15 06:50:46.960653+00 |
| description | Simple macro to use go-defer-like in Rust |
| homepage | |
| repository | https://github.com/open1s/rgo |
| max_upload_size | |
| id | 1634029 |
| size | 20,890 |
A scope guard will run a given closure when it goes out of scope, even if the code between panics (as long as panic doesn't abort).
Add this to your Cargo.toml:
[dependencies]
rgo = "0.2.0"
extern crate rgo;
fn f() {
let _guard = rgo::guard((), |_| {
println!("Hello Scope Exit!");
});
// rest of the code here
// Here, at the end of `_guard`'s scope, the guard's closure is called
// It is also called if we exit this scope through unwinding instead
}
defer! Macro#[macro_use(defer)] extern crate rgo;
use std::cell::Cell;
fn main() {
let drop_counter = Cell::new(0);
{
defer! {
drop_counter.set(1 + drop_counter.get());
}
// Do regular operations here
assert_eq!(drop_counter.get(), 0);
}
assert_eq!(drop_counter.get(), 1);
}
extern crate rgo;
use std::fs::File;
use std::io::{self, Write};
fn try_main() -> io::Result<()> {
let f = File::create("newfile.txt")?;
let mut file = rgo::guard(f, |f| {
// ensure we flush file at return or panic
let _ = f.sync_all();
});
file.write_all(b"test me\n").map(|_| ())
}
use_std (enabled by default): Enables the OnUnwind and OnSuccess strategiesuse_std to use no_stdThis crate requires Rust 1.20 or later.