Ownership and functions
A function parameter is a new variable that receives the argument at the call. So a function call follows the same ownership rules as let. Giving a string to a function is like handing over the key to a unit: it comes back only if the function hands it back itself.
The argument moves into the parameter
fn print_twice(s: String) {
println!("{s} {s}");
}
fn square(n: i32) -> i32 {
n * n
}
fn main() {
let name = String::from("Anna");
print_twice(name); // Anna Anna
let x = 7;
println!("{} {x}", square(x)); // 49 7
}Let's go step by step:
namebecomes the owner of the stringAnna.print_twice(name)moves the string into the parameters, likelet s = name;. Now the owner iss, andnamehas been moved.- The function prints
Anna Anna. - At the
}of the functionprint_twice, the parametersgoes out of scope, and the string is destroyed right there. square(x)gets a copy of the number:i32is aCopytype, andxstays usable after the call.- The last line prints
49 7.
After the call print_twice(name) you cannot use name: the string is gone. A function that takes a String takes it for good.
Returning hands ownership back
A function can give the key back: the value it returns moves to the calling code. String::from itself works this way: it creates a string and hands ownership to you.
fn add_mark(mut s: String) -> String {
s.push('!');
s
}
fn main() {
let name = String::from("Anna");
let name = add_mark(name);
println!("{name}"); // Anna!
}Let's go step by step:
add_mark(name)moves the string into the parameters.mutbefore the parameter lets the function change its string, likelet mut.s.push('!')adds a character.- The last expression without
;is the value of the function. The expressionsmoves the string out of the function back to the calling code. let name =shadows the movednamewith a new variable, which becomes the owner of the stringAnna!.
This technique is called "take and give back". It works, but if the function only needs to read the string, passing it there and back is awkward.
The drop function
The standard library has a function drop that does the same to its argument as print_twice, except that it prints nothing. drop(s) takes the value, and its body is empty. At its } the value is destroyed, and the space on the heap is freed before the block ends. After drop(s) the variable s has been moved, as after any call with a String.
Here the key analogy falls short. In real life a key is lent for a while, and the person gives it back. In Rust, a function with a String parameter does not have to return anything: if it does not hand the string back as its result, the key never comes back.
Interviewers like to ask this: "What happens to a String that is passed to a function?" The answer:
- the string moves into the parameter, and the calling code can no longer use it;
- when the function returns, the parameter goes out of scope, and the string is destroyed;
- for the string to come back, the function must hand it back as its result;
- a number or another
Copytype is copied, and the variable stays usable.
Common mistake
A string is used after it was given to a function:
fn print_twice(s: String) {
println!("{s} {s}");
}
fn main() {
let name = String::from("Anna");
print_twice(name);
println!("{name}"); // ✗
}error[E0382]: borrow of moved value: `name`The program does not compile: print_twice(name) took the string, and by the function's } it is already destroyed. This is a compile error, not a panic: the compiler tracks every move, including a move into a function argument. There are two ways to fix it:
- return the string from the function, as
add_markdoes; - pass a copy,
print_twice(name.clone()), if you really need a copy.
Key points
- Passing a
Stringto a function moves ownership into the parameter, asletdoes. - When the function returns, the parameter goes out of scope, and the string is destroyed unless it was returned.
- A returned value hands ownership to the calling code.
- Numbers and other
Copytypes are passed as copies, and the variable stays usable.