Alexander Yurchenko

Ownership, borrowing, and lifetimes in practice

Created
Updated
Author
Alexander Yurchenko

A function can count the bytes in a ticket label just by reading the string. Pass a reference for the read, then use a different borrow to update the same string. The compiler checks that the two operations are compatible.

Moving and copying

  • Move. The assignment let mut current = original transfers ownership of the String. The buffer contents stay in place, and the old binding original is no longer usable. Dropping the owned String releases the buffer allocation.
  • Copy. The type u32 implements Copy. Assignment copies the number, and both bindings remain usable. Use clone if you need two independent copies of a string.

Array assignment in PHP preserves value semantics and typically uses copy-on-write. Assigning an object variable gives two variables access to the same object. In both cases the original variable remains usable. See the chapter on ownership for Rust's rules for moves.

Borrows and lifetimes

  • Shared reference. label_len takes an &str and reads the label without allocating another buffer. Multiple shared references to the same data can be in use at once.
  • Exclusive mutable reference. add_suffix takes an &mut String and updates the string in place. While that borrow is in use, it cannot overlap with another borrow of the same data. The compiler tracks the reference's last use, which can occur before the end of the block.

longer returns one of two references. The lifetime parameter 'a ties the result to both inputs. You can use the result only while both borrows remain valid. The annotation describes that relationship and does not keep either string alive. The find function from the lesson on structs and error handling has just one borrowed input. Rust ties the returned reference to it automatically through lifetime elision. See the chapter on lifetimes.

In the Cargo demo project, replace the entire src/main.rs and run cargo run. The str::len method measures bytes, so longer compares byte lengths. The byte count matches the number of visible characters for these ASCII labels.

RUST
fn label_len(label: &str) -> usize {
    label.len()
}

fn add_suffix(label: &mut String) {
    label.push_str("-closed");
}

fn longer<'a>(left: &'a str, right: &'a str) -> &'a str {
    if left.len() >= right.len() { left } else { right }
}

fn main() {
    let original = String::from("ticket");
    let mut current = original;
    let bytes = label_len(&current);
    println!("bytes: {}", bytes);
    // The shared borrow used to read the label is already finished.
    add_suffix(&mut current);
    // The result borrows one of the strings without allocating a new buffer.
    let chosen = longer(&current, "open");
    println!("{}", chosen);
    let id = 42_u32;
    let copied_id = id;
    println!("{} {}", id, copied_id);
}

TEXT
bytes: 6
ticket-closed
42 42

Three deliberate compilation errors

Open a terminal in the directory containing the files. A direct rustc invocation defaults to edition 2015 for backward compatibility. Pass --edition=2024 to use the same mode as the Cargo project. See the rustc documentation.

Using a value after a move

Save this as moved.rs and run rustc --edition=2024 moved.rs.

RUST
fn main() {
    let label = String::from("ticket");
    let current = label;
    // The old binding cannot access the string after the move.
    println!("{} {}", current, label);
}

E0382 points to the use of label after it has moved. Print through current, which now owns the string.

Overlapping mutable borrows

Save this as overlapping.rs and pass that filename to the same command.

RUST
fn main() {
    let mut label = String::from("ticket");
    let first = &mut label;
    // The first borrow is still used below, so the second borrow overlaps it.
    let second = &mut label;
    first.push_str("-a");
    second.push_str("-b");
}

E0499 occurs because first is still needed after second is created. Move first.push_str("-a") above the declaration of second to finish the first borrow before the second starts.

A reference outlives its owner

Save this as expired.rs and pass that filename to the compiler.

RUST
fn main() {
    let borrowed;
    {
        let label = String::from("ticket");
        // The owner will be dropped at the end of this block, before the reference is used.
        borrowed = &label;
    }
    println!("{}", borrowed);
}

E0597 means label is dropped before borrowed is read. Declare a binding in the outer block and assign it the string itself from the inner block. That moves the String out. You can also keep the owner in the outer scope from the start.

Summary

The signature tells you whether a reference is enough or the function needs ownership. The same applies to dependencies. In the lesson on traits and dependencies, a service will store the formatter it receives.