borrowing

Rust Prevent dangling references

A reference must refer to valid storage for all its uses. A loan cannot be used after the owning local has been destroyed. Organize owners and consumers so the reference remains valid; do not try to repair an invalid owner lifetime by adding an annotation. Expected output (not executed): Box 2 Kept: Box 2 Why: The owner lives through the inner borrow and is still available afterward. Common mistake: Creating a String in an inner block and trying to read its reference outside that block.

Formal Syntax & Structure

rust syntaxrust
let owner = ...; let view = &owner;

Working Example

Example Snippetrust
fn main() {    let label = String::from("Box 2");    {        let view = &label;        println!("{view}");    }    println!("Kept: {label}");}
Rust Reference