lifetime

Rust Distinguish a stored reference from a receiver borrow

A method can explicitly return a copy of a stored shared reference with its original lifetime. That relationship differs from the shorter borrow of self. It is not a way to return a reference to owned fields after the struct is gone. Expected output (not executed): done Why: The returned shared reference targets message, which still exists after wrapper is gone. Common mistake: Replacing the return type with &str and expecting the same receiver-independent guarantee.

Formal Syntax & Structure

rust syntaxrust
impl<'a> View<'a> { fn text(&self) -> &'a str { ... } }

Working Example

Example Snippetrust
struct View<'a> { data: &'a str }impl<'a> View<'a> {    fn text(&self) -> &'a str { self.data }}fn main() {    let message = String::from("done");    let result;    {        let wrapper = View { data: &message };        result = wrapper.text();    }    println!("{result}");}
Rust Reference