Ownership across functions in Rust
A function can take ownership, borrow, or hand ownership back.
fn consume(text: String) -> usize {
text.len()
}
fn inspect(text: &String) -> usize {
text.len()
}
fn hand_back(mut text: String) -> String {
text.push_str("!");
text
}
fn main() {
let greeting = String::from("welcome");
println!("{}", inspect(&greeting));
let greeting = hand_back(greeting);
println!("{}", consume(greeting));
}
How it works
- Taking
Stringconsumes the caller's value. - Taking
&Stringborrows and leaves it usable. - Returning the value passes ownership back out.
Keywords and builtins used here
Stringconsumefnhand_backinspectletmainmutusize
The run, in numbers
- Lines
- 19
- Characters to type
- 332
- Tokens
- 106
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 71 seconds.
Step 3 of 3 in Move & clone, step 3 of 15 in Ownership & borrowing.