Rustlers Atom 2.11: Returning references

Returning references is one of the most common stumbling blocks for new Rustaceans. The rule is simple but strict: You cannot return a reference to something created inside the function.

Why? Because when the function returns, its stack frame is destroyed. Any variable created inside that function (that isn't returned by ownership) is dropped. If you returned a reference to it, you would be pointing to freed memory.

The Dangling Reference (Forbidden)

fn create_dangling() -> &String { // ❌ Missing lifetime specifier
    let s = String::from("hello");
    &s // ❌ Error: `s` is dropped here while still borrowed
}

The compiler will reject this with: "returns a value referencing data owned by the current function". If the function builds a new value, it must return ownership of that value, not a reference.

fn create_owned() -> String {
    let s = String::from("hello");
    s // ✅ Move ownership out
}

Valid Case: Passthrough References

You can return a reference if it refers to data that existed before the function was called. In this case, the output reference shares the lifetime of the input reference.

// This function takes a reference and returns a reference.
// Rust assumes the output lives as long as the input.
fn pick_first(a: &str, b: &str) -> &str {
    if a.len() < b.len() {
        a
    } else {
        b
    }
}

fn main() {
    let string1 = String::from("short");
    let string2 = String::from("longer");

    let result = pick_first(&string1, &string2);
    println!("Selected: {}", result);
}

In pick_first, no new data is created. We are just passing a view through the function. The data lives in main, so the references are valid.

Valid Case: String Literals (`static)

You can also return a string literal. Literals are baked into the binary and live forever (the 'static lifetime), so it is always safe to return a reference to them.

fn get_default_name() -> &'static str {
    "Anonymous" // Valid because it points to static memory
}

You'll only receive email when they publish something new.

More from GSLF
All posts