macro_rules! defer {
( $($tt:tt)* ) => { ... };
}
Expand description
Executes a block of code when the surrounding scope ends.
§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, however, 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");
}