Expand description
Executes the scope scope
.
A scope is a closure, in which access to a guard is granted.
A guard is used to schedule callbacks to run on a scope’s success, failure, or exit.
For more information on how to use the guard, see Guard
.
The scope is required to return a type implementing Failure
,
to indicate whether the scoped exited with success, or failure.
Examples
use scoped::{Guard, scoped};
fn main() {
use std::cell::Cell;
let mut n = Cell::new(0);
scoped(|guard| -> Result<(), ()> {
guard.on_scope_exit(|| {
assert_eq!(n.get(), 2);
n.set(3);
});
guard.on_scope_success(|| {
assert_eq!(n.get(), 1);
n.set(2);
});
n.set(1);
Ok(())
});
assert_eq!(n.get(), 3);
}
A callback can also be cancelled, using Handle::cancel
use scoped::{Guard, scoped};
fn main() {
let mut v = vec![1, 2, 3];
scoped(|guard| -> Option<()> {
let mut handle = guard.on_scope_exit_with(&mut v, |vec| {
panic!()
});
handle.push(4);
let cancelled = handle.cancel();
cancelled.push(5);
Some(())
});
assert_eq!(v, vec![1, 2, 3, 4, 5]);
}