Ownership and move in Rust
Every value has one owner; passing it moves it.
fn takes_ownership(s: String) -> usize {
s.len()
}
fn main() {
let text = String::from("hello");
let n = takes_ownership(text);
// `text` has moved into the function; only `n` remains
let a = String::from("keep");
let b = a.clone();
println!("{n} {a} {b}");
}
How it works
- Passing a
Stringmoves it into the function. - After a move the original binding is unusable.
clonemakes an independent copy to keep both.
Keywords and builtins used here
Stringfnletmaintakes_ownershipusize
The run, in numbers
- Lines
- 13
- Characters to type
- 261
- Tokens
- 71
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 47 seconds.
Step 1 of 3 in Move & clone, step 1 of 15 in Ownership & borrowing.