pub struct DeferGroup<'a>(/* private fields */);
Expand description
A utility struct for explicitly scoped deferred execution of closures.
The DeferGroup
allows you to add closures (functions) that will be executed
when the DeferGroup
instance goes out of scope. It is particularly useful
for resource cleanup or deferred actions.
Note: DeferGroup
MUST be bound to a variable to function properly; otherwise, it will be dropped immediately, executing the enclosed closures!
§Example
use defer_rs::DeferGroup;
let mut defer_group = DeferGroup::new();
// Add a function to be executed when `defer_group` goes out of scope
defer_group.add(Box::new(|| {
println!("Deferred action: Cleaning up resources...");
}));
// Some other code...
// The deferred (queued) actions will be executed here, when the `defer_group` is dropped.
See also: defer_scope!
, defer_scope_init!
, Defer
, and defer!
.
Implementations§
Source§impl<'a> DeferGroup<'a>
impl<'a> DeferGroup<'a>
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new DeferGroup
.
Note: DeferGroup
MUST be bound to a variable to function properly; otherwise, it will be dropped immediately, executing the enclosed closures!
§Example
use defer_rs::DeferGroup;
let mut defer_group = DeferGroup::new();
// Add deferred actions...
Sourcepub fn add(&mut self, f: Box<dyn FnOnce() + 'a>)
pub fn add(&mut self, f: Box<dyn FnOnce() + 'a>)
Adds a deferred closure to the start (0-index) of the DeferGroup
queue.
The closures queued in DeferGroup
will be executed first to last
when the the DeferGroup
instance goes out of scope.
§Example
use defer_rs::DeferGroup;
let mut defer_group = DeferGroup::new();
{
defer_group.add(Box::new(|| {
println!("This will be printed 2nd");
}));
defer_group.add(Box::new(|| {
println!("This will be printed 1st");
}));
}
Sourcepub fn push(&mut self, f: Box<dyn FnOnce() + 'a>)
pub fn push(&mut self, f: Box<dyn FnOnce() + 'a>)
Pushes a deferred closure to the end of the DeferGroup
queue.
The closures queued in DeferGroup
will be executed first to last
when the the DeferGroup
instance goes out of scope.
§Example
use defer_rs::DeferGroup;
let mut defer_group = DeferGroup::new();
{
defer_group.push(Box::new(|| {
println!("This will be printed 1st");
}));
defer_group.push(Box::new(|| {
println!("This will be printed 2nd");
}));
}