Sub topic 6
Passing and returning ownership with functions
This chapter assumes you know basic Rust syntax (functions, structs, enums), can build and run a program with cargo, and have read the earlier chapters on the ownership rules, scope and Drop, moves, and Copy versus Clone. Here we apply those ideas to function calls.
Function calls are moves
Passing a value to a function works like assigning it to a new variable. The argument either moves or copies into the parameter. A String moves. An i32 is Copy, so it is duplicated.
fn takes_ownership(s: String) {
println!("got {s}");
} // `s` is dropped here, and its heap memory is freed
fn makes_copy(n: i32) {
println!("got {n}");
} // `n` goes out of scope, and nothing special happens
fn main() {
let text = String::from("hello");
takes_ownership(text);
// println!("{text}"); // error: borrow of moved value: `text`
let number = 5;
makes_copy(number);
println!("{number}"); // still valid because i32 is Copy
}After takes_ownership(text), the variable text in main is no longer valid. The parameter s is now the owner. When the function ends, s goes out of scope and Drop runs, which frees the heap buffer. The caller has no say in when this happens.
The compiler tracks this statically. It does not insert a runtime flag in the simple case. It rejects any later use of text, so a double free or use-after-free cannot happen.
Returning ownership
A function can hand ownership back to its caller through its return value. The value moves out of the function instead of being dropped.
fn gives_ownership() -> String {
let s = String::from("from function");
s // moved out to the caller
}
fn takes_and_gives_back(s: String) -> String {
s // moved back out
}
fn main() {
let a = gives_ownership();
let b = String::from("round trip");
let c = takes_and_gives_back(b);
// `b` was moved into the function, so only `a` and `c` are valid.
println!("{a} {c}");
}Returning a local variable is safe. Nothing refers to the local after the function ends, because ownership moves with the value. The heap buffer is not copied in this case. Only the small stack part (pointer, length, capacity) is moved.
The following diagram shows who owns the string at each step.
The cost of passing ownership back and forth
Suppose a function only needs to read a value, but the caller wants to keep using it. If the function takes ownership, the caller must get it back. One way is to return it along with the result, using a tuple.
fn calculate_length(s: String) -> (String, usize) {
let length = s.len();
(s, length)
}
fn main() {
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
println!("'{s2}' is {len} bytes");
}This works, but it is clumsy. Every function that merely inspects data would have to return it. Rust solves this with references, which let a function use a value without owning it. The next chapters cover them. For now, treat this tuple pattern as the motivation, and as a way to recognize what the code is doing when you see it.
Choosing a parameter type
The type of a parameter states what the function does with the argument. This table summarizes the common choices.
| Parameter type | What the caller gives up | Typical use |
|---|---|---|
| `String` | The value (moved) | The function stores it, consumes it, or returns it |
| `&str` or `&String` | Nothing (shared borrow) | The function only reads |
| `&mut String` | Nothing permanent (exclusive borrow) | The function modifies it in place |
| `i32` and other `Copy` types | Nothing (a copy is made) | Small values, passed by value |
A useful rule: take ownership only when the function needs to keep, store, or consume the value. Otherwise borrow it.
Consuming functions and builders
Some functions take ownership on purpose. A method that takes self consumes its receiver. The standard library does this often, for example into_iter, into_bytes, and String::into_boxed_str. Naming conventions help: methods starting with into_ usually take self by value.
struct Order {
items: Vec<String>,
}
impl Order {
fn new() -> Self {
Order { items: Vec::new() }
}
// Takes `self` by value and returns it, which allows chaining.
fn add(mut self, item: &str) -> Self {
self.items.push(item.to_string());
self
}
// Consumes the order and returns its contents.
fn into_items(self) -> Vec<String> {
self.items
}
}
fn main() {
let order = Order::new().add("tea").add("bread");
let items = order.into_items();
// `order` was consumed, so it cannot be used here.
println!("{:?}", items);
}The mut self in add makes the owned parameter mutable. It does not make the caller's variable mutable, because the caller gave the value away. This builder style is common because ownership moves through each call without any copying of the heap data.
Partial moves and struct fields
Moving a field out of a struct moves only that field. The rest of the struct stays usable, as long as the struct does not implement Drop.
struct Person {
name: String,
age: u32,
}
fn main() {
let p = Person {
name: String::from("Ada"),
age: 36,
};
let name = p.name; // partial move: only `name` leaves `p`
println!("{name} is {}", p.age); // `age` is Copy and still in `p`
// println!("{}", p.name); // error: use of moved value
}You cannot pass p as a whole after the partial move, because part of it is gone. If Person implemented Drop, the compiler would reject the field move entirely, since drop needs the whole value intact.
Common errors and fixes
These are the mistakes you will meet most often with functions and ownership.
- Using a value after passing it. The error reads
borrow of moved value. Fix it by borrowing (&value) if the function only reads, by cloning (value.clone()) if it truly needs its own copy, or by having the function return the value. - Moving inside a loop. Calling
consume(s)in each iteration movesson the first pass. The error readsvalue moved here, in previous iteration of loop. Pass a reference or clone inside the loop. - Moving out of a borrowed value. Writing
let s = v[0];on aVec<String>fails withcannot move out of index. A vector cannot give up one element and leave a hole. Use&v[0],v[0].clone(), orv.remove(0)depending on what you need. - Returning a reference to a local. A function cannot return
&sfor a locals, becausesis dropped at the end of the function. Return the owned value instead. The chapter on dangling references covers this.
fn consume(s: String) {
println!("{s}");
}
fn main() {
let s = String::from("repeat");
for _ in 0..2 {
consume(s.clone()); // each iteration gets its own copy
}
consume(s); // the last use can move the original
}The last call moves s instead of cloning it. When you clone in a loop, you can skip the clone on the final use and avoid one allocation.
Moves are cheap, clones are not
A move copies only the stack part of the value. For a String, that is three machine words, however long the text is. Passing a ten-megabyte String by value is as cheap as passing a short one. A clone allocates new heap memory and copies every byte. When performance matters, prefer moves and borrows, and clone only when two independent owners are needed.
Summary of the model
- Passing an argument by value moves it, unless the type is
Copy. - The parameter owns the value and drops it when the function ends, unless the function returns it or moves it elsewhere.
- Returning a value moves ownership to the caller.
- Methods taking
selfconsume the receiver. - Moving a field is a partial move, and it leaves the other fields usable.
- Prefer borrowing when the function does not need to own the value.
Exercise
The code below does not compile. Explain why, then give two different fixes. fn shout(s: String) -> usize { println!("{}!", s.to_uppercase()); s.len() } fn main() { let name = String::from("ferris"); let n = shout(name); println!("{name} has {n} bytes"); }
Show answer
shout takes String by value, so name is moved into it and is invalid after the call. The later println! uses a moved value. Fix 1: change the parameter to s: &str and call shout(&name), so name is only borrowed. Fix 2: call shout(name.clone()), which passes a separate copy and leaves name valid, at the cost of one heap allocation. A third option is to have shout return the string alongside the length.
Exercise
What does this program print, and in what order are the values dropped? struct Noisy(&'static str); impl Drop for Noisy { fn drop(&mut self) { println!("dropping {}", self.0); } } fn pass(n: Noisy) -> Noisy { println!("in pass"); n } fn main() { let a = Noisy("a"); let b = pass(a); println!("main ends"); }
Show answer
It prints "in pass", "main ends", then "dropping a". The value a moves into pass and is returned unchanged, so it is not dropped inside the function. It moves into b, which is dropped when main ends. The variable a is no longer valid after the call, so only one drop happens.