Why can't I return a reference to a local variable

Rust forbids returning references to local variables because the data they point to is destroyed when the function ends.

You cannot return a reference to a local variable because the variable is dropped when the function ends, leaving the reference pointing to invalid memory. Rust prevents this at compile time to ensure memory safety.

fn bad() -> &String {
    let s = String::from("hello");
    &s // Error: `s` is dropped here, reference becomes invalid
}

To fix this, return the owned value instead of a reference, or return a reference to data that lives longer than the function.