lifetime
Rust Borrowed trait object lifetime bound
A trait object can hide a concrete type that contains borrowed fields. The object lifetime bound limits those hidden borrows. An owned Box does not necessarily mean its contents are independent of every external reference. In a type position, Box<dyn Trait> commonly defaults to a static object bound when no other rule applies. Expected output (not executed): Parcel Why: The Box owns the concrete Borrowed wrapper, which borrows name. The object bound permits that relationship. Common mistake: Removing + 'a from the return type and assuming the function elision rules for references automatically apply to the trait object.
Formal Syntax & Structure
rust syntaxrust
Box<dyn Trait + 'a>Working Example
Example Snippetrust
trait Label { fn text(&self) -> &str; }struct Borrowed<'a>(&'a str);impl Label for Borrowed<'_> { fn text(&self) -> &str { self.0 } }fn boxed<'a>(s: &'a str) -> Box<dyn Label + 'a> { Box::new(Borrowed(s))}fn main() { let name = String::from("Parcel"); let label = boxed(&name); println!("{}", label.text());}