lifetime
Rust Higher-ranked trait objects
A dynamically dispatched callback can expose a lifetime-polymorphic input contract. The lifetime of the trait object itself is a separate constraint from the lifetimes of the arguments it accepts. Expected output (not executed): 5 Why: The borrowed callback can read its captured local extra and accept another local borrow. Common mistake: Confusing universal argument lifetimes with a static requirement for the callback object.
Formal Syntax & Structure
rust syntaxrust
&dyn for<'a> Fn(&'a str) -> usizeWorking Example
Example Snippetrust
fn main() { let extra = 2; let counter = |s: &str| s.len() + extra; let callback: &dyn for<'a> Fn(&'a str) -> usize = &counter; let local = String::from("box"); println!("{}", callback(&local));}