Who owns this value?.
Follow a heap-owning value as responsibility changes hands.
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.
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}");
}engine / ready
- 1
The first-to-second assignment moves the String.
- 2
label takes ownership and may mutate its local binding.
- 3
The returned String becomes owned by result and is dropped at the end of main.
cargo run -p lesson_ownership03 Mind the boundary
04 Your next build
Write a function that takes ownership of a String, adds an exclamation mark, and returns it.
Reveal one possible solution +
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
After let b = a for a String, who owns the original allocation?
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.