Sub topic 6
Passing and returning ownership with functions
This chapter assumes you know basic Rust syntax, can run a program with cargo, and have read the previous chapters on the ownership rules and moves. Here you will see how those rules apply when a value crosses a function boundary.
Passing a value moves it
Passing an argument to a function works like assigning it to a new variable. A type that is not Copy is moved into the parameter. The function now owns the value and drops it when the function ends.
fn consume(s: String) {
println!("got {s}");
} // s is dropped here
fn main() {
let text = String::from("hello");
consume(text);
// println!("{text}"); // error: borrow of moved value: `text`
}A Copy type such as i32 is copied instead, so the caller can keep using it.
Returning ownership
A function can hand ownership back through its return value. The caller then owns the result and is responsible for it.
fn make_greeting() -> String {
String::from("hello")
}
fn add_exclamation(mut s: String) -> String {
s.push('!');
s
}
fn main() {
let a = make_greeting();
let b = add_exclamation(a);
println!("{b}");
}Here a moves into add_exclamation, and the same heap buffer returns as b. Nothing is copied or freed in between.
The cost of giving ownership away
If you only want to read a value, moving it in forces you to return it so the caller can use it again. You can do that with a tuple:
fn length(s: String) -> (String, usize) {
let n = s.len();
(s, n)
}
fn main() {
let s = String::from("hello");
let (s, n) = length(s);
println!("{s} has {n} bytes");
}This works, but it is awkward. Every function that merely inspects a value would need to hand it back. Borrowing, covered in the next chapters, solves this.
fn length(s: &str) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = length(&s);
println!("{s} has {n} bytes");
}Choosing a parameter type
| Parameter | Caller keeps the value? | Use when the function |
|---|---|---|
| `String` | No, it is moved | stores the value, or consumes it |
| `&str` or `&String` | Yes | only reads it |
| `&mut String` | Yes, and sees changes | modifies it in place |
Common errors
- Using a value after passing it. The compiler reports "borrow of moved value". Pass a reference, or call
.clone()if the function needs its own copy. - Returning a reference to a local variable. The local is dropped at the end of the function, so the reference would dangle. Return the owned value instead. The dangling references chapter covers this in detail.
- Cloning to silence the compiler.
.clone()compiles but allocates and copies. Prefer a reference when the function does not need ownership.
Exercise
A function has the signature fn print_len(s: String). After print_len(name); in main, why can't you use name, and how do you change the signature so you can?
Show answer
Passing name moves the String into the function, which drops it at the end. Change the parameter to s: &str and call print_len(&name);. The function then borrows the value, and name stays valid in main.