Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ OWNERSHIP WITHOUT THE PANIC
BUILD NOTE 09 / 53

Who owns this value?.

Follow a heap-owning value as responsibility changes hands.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

A value has an owner responsible for dropping it when its lifetime ends. Assigning a String to another binding transfers ownership rather than duplicating its heap allocation. The original binding is then unavailable. Passing an owned value into a function can transfer ownership in the same way; returning it can transfer it back. This makes cleanup predictable without requiring a garbage collector. Distinguish the owned String from an &str reference, which temporarily views text owned elsewhere.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/ownership/src/main.rs
fn label(mut name: String) -> String {
    name.push_str(" / ready");
    name
}
fn main() {
    let first = String::from("engine");
    let second = first;
    let result = label(second);
    println!("{result}");
}
↳ EXPECTED OUTPUT
engine / ready
  1. 1

    The first-to-second assignment moves the String.

  2. 2

    label takes ownership and may mutate its local binding.

  3. 3

    The returned String becomes owned by result and is dropped at the end of main.

From the extracted rust-workbench folder
cargo run -p lesson_ownership

03 Mind the boundary

04 Your next build

A SMALL MISSION

Write a function that takes ownership of a String, adds an exclamation mark, and returns it.

Reveal one possible solution +
solutions/ownership/src/main.rs
fn excite(mut text: String) -> String {
    text.push('!');
    text
}
fn main() {
    let text = excite(String::from("Build"));
    assert_eq!(text, "Build!");
}

05 Check your reasoning

QUICK SIGNAL CHECK

After let b = a for a String, who owns the original allocation?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.