Why Can't I Return a Reference to a Local Variable in Rust?

Rust forbids returning references to local variables because they are dropped when the function ends, creating invalid memory pointers.

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. Instead, return the owned value or borrow from an argument passed into the function.

fn get_string() -> String {
    let s = String::from("hello");
    s // Return the owned String, not a reference
}

fn get_first_word(s: &str) -> &str {
    // Return a reference to data owned by the caller
    if let Some(space) = s.find(' ') {
        &s[..space]
    } else {
        s
    }
}