Guide

Dangling references

A reference points at a value that someone else owns. The one big rule: a reference must not outlive the value it points to. If the value is dropped while the reference is still in use, the reference would point at freed memory. That is a dangling reference, and Rust refuses to compile it.

A reference can't outlive its value

let r;{    let x = 5;    r = &x;}                // x is dropped hereprintln!("{r}"); // error E0597

x lives only inside the block. r is still used after the block, so x does "not live long enough". To fix it, make the value live longer, or stop using the reference sooner.

Returning a reference to a local

A function's local variables are dropped when the function returns. So a function can't hand out a reference to one of them.

fn make() -> &String {    // error E0106    let s = String::from("hi");    &s}

With no reference inputs, there is nothing the result could borrow from, so Rust asks for a lifetime (E0106). If the function does take a reference, Rust sees the real problem and reports E0515: "cannot return reference to local variable".

Returning a reference to something the caller passed in is fine, because the caller still owns it:

fn first(v: &Vec<i32>) -> &i32 {    &v[0]}

Return an owned value instead

When a function builds new data, return the data itself, not a reference. Ownership moves out to the caller, so nothing dangles.

fn shout(s: &str) -> String {    s.to_uppercase()}

s.to_uppercase() builds a new String with every letter in capitals. format! also builds a new String, so return those as String too.

Remember

  • A reference must not outlive its value.
  • E0597: the value does not live long enough.
  • E0515: you returned a reference to a local.
  • E0106: Rust needs to know what the result borrows from.
  • If the function makes new data, return String, not &str.