Expand description
Safely use (stack) references outside their original scope.
§Example
use ref_portals::rc::Anchor;
let x = "Scoped".to_owned();
let anchor = Anchor::new(&x);
let self_owned: Box<dyn Fn() + 'static> = Box::new({
let portal = anchor.portal();
move || println!("{}", *portal)
});
self_owned(); // Scoped
Note that dropping anchor
before self_owned
would still cause a panic here.
You can use weak portals to work around this:
use ref_portals::rc::Anchor;
let x = "Scoped".to_owned();
let anchor = Anchor::new(&x);
let eternal: &'static dyn Fn() = Box::leak(Box::new({
let weak_portal = anchor.weak_portal();
move || println!(
"{}",
*weak_portal.upgrade(), // Panics iff the anchor has been dropped.
)
}));
eternal(); // Scoped
§Notes
Panic assertions in this documentation use assert_panic.