RUST / CHAPTER 02
Ownership and moved values
IntermediateExplain when an owned value moves and when an independent copy is created.
By the end of this chapter
- Trace String ownership transfers
- Distinguish Copy from clone
- Design a consuming function boundary
The idea
Enter with bindings and function calls understood. Each owned value has an owner responsible for dropping it. Assigning a String to another binding normally moves ownership: the old binding is no longer usable. This rule prevents two owners from independently freeing the same allocation. Simple scalar types such as i32 implement Copy, so assignment duplicates their value instead.
A function parameter can also receive ownership. After passing a String by value, the caller cannot use its old binding unless ownership is returned. clone requests an independent owned copy when that is actually needed; it may allocate and copy data. Choose a consuming interface when ownership transfer is meaningful, and prefer borrowing when a helper merely inspects data. These choices make resource lifetimes visible in the types.
fn main(){
let original=String::from("orbit");
let copy=original.clone();
let moved=original;
println!("{} {}",copy,moved);
}orbit orbit
clone creates independent string storage. Moving original into moved transfers its ownership, leaving copy available independently.
Try it yourself
Write a function that consumes a String and returns its length; identify which caller binding becomes unavailable.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING