Skip to main content

How to Pass a Reference to a Function in Rust

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

Passing a String to a Rust function moves it: the function becomes its owner, and the caller can't use it anymore. Pass a reference with & instead, and the function only borrows the value, so it's still yours afterwards.

Syntax​

Syntax
fn <name>(<param>: &<Type>) { … }
fn <name>(<param>: &mut <Type>) { … }

<name>(&<value>);
<name>(&mut <value>);
PartWhat it does
& before the parameter's typeThe parameter is a shared reference: the function can read the value but not change it.
&mut before the parameter's typeThe parameter is a mutable reference: the function can change the value.
& before the argumentCreates a reference to the value, lending it to the function.
&mut before the argumentCreates a mutable reference. The value must be declared with let mut.

The Rust Book's chapter on references and borrowing: "A reference is like a pointer in that it’s an address we can follow to access the data stored at that address; that data is owned by some other variable." And: "We call the action of creating a reference borrowing."

The Example​

The example's print_length function prints a name and its number of letters. main lends it the same String twice, then still prints the name itself.

Prerequisites​

  • Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.0.

Step 1: Create a Project​

Terminal
cargo new demo
cd demo
Output
Creating binary (application) `demo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

cargo new demo creates a folder named demo with a Cargo.toml file, which describes the project, and src/main.rs, which holds the code. cd demo moves into it.

Step 2: Write the Code​

Replace the contents of src/main.rs with:

src/main.rs, where print_length takes text as a str reference and prints its length, and main creates the String Ada, passes and name twice, and prints that the name is still here.

src/main.rs
fn print_length(text: &str) {
println!("{text} has {} letters", text.len());
}

fn main() {
let name = String::from("Ada");
print_length(&name);
print_length(&name);
println!("{name} is still here");
}

text: &str means print_length borrows the text instead of taking it. &name lends the String for the length of the call. &name is a &String, and Rust turns it into the &str the function asks for, a conversion the Rust Book calls deref coercion.

Step 3: Run It​

Terminal
cargo run -q
Output
Ada has 3 letters
Ada has 3 letters
Ada is still here

A zsh terminal where cargo run -q prints Ada has 3 letters twice and then Ada is still here.

cargo run compiles the program and runs it, and -q hides Cargo's own status lines. Each call borrowed name and gave it back, so main could lend it a second time and print it at the end.

Without the &​

Here print_length takes a String and main passes name itself, once:

src/main.rs
fn print_length(text: String) {
println!("{text} has {} letters", text.len());
}

fn main() {
let name = String::from("Ada");
print_length(name);
println!("{name} is still here");
}

The call moves the String into the function, so the build stops at the last line, which uses name after the move:

Output
error[E0382]: borrow of moved value: `name`
--> src/main.rs:8:16
|
6 | let name = String::from("Ada");
| ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
7 | print_length(name);
| ---- value moved here
8 | println!("{name} is still here");
| ^^^^ value borrowed here after move
|
note: consider changing this parameter type in function `print_length` to borrow instead if owning the value isn't necessary
--> src/main.rs:1:23
|
1 | fn print_length(text: String) {
| ------------ ^^^^^^ this parameter takes ownership of the value
| |
| in this function
help: consider cloning the value if the performance cost is acceptable
|
7 | print_length(name.clone());
| ++++++++

For more information about this error, try `rustc --explain E0382`.
error: could not compile `demo` (bin "demo") due to 1 previous error

The compiler's note points at the fix this guide uses: make the parameter borrow.

Change a Value Through &mut​

A mutable reference lets a function change the caller's value:

src/main.rs
fn add_title(text: &mut String) {
text.insert_str(0, "Dr. ");
}

fn main() {
let mut name = String::from("Ada");
add_title(&mut name);
println!("{name}");
}
Output
Dr. Ada

insert_str(0, "Dr. ") adds the text at the start, and the change shows in main because the function worked on main's own String.

Common Mistakes​

MistakeWhat happensDo this instead
Passing name to a function that takes &strerror[E0308]: mismatched types, expected `&str`, found `String` , with the help consider borrowing herePass &name
Passing a String by value and using it afterwardserror[E0382]: borrow of moved value: `name` Make the parameter a reference
&mut on a variable declared without muterror[E0596]: cannot borrow `name` as mutable, as it is not declared as mutableDeclare it with let mut

Troubleshooting​

SymptomLikely causeFix
value borrowed here after moveThe value moved into an earlier callPass a reference with &
expected `&str`, found `String` The & is missing in the callAdd & before the argument

FAQ​

How many references can I have at once?​

The Book's rule: "At any given time, you can have either one mutable reference or any number of immutable references." The compiler checks it for you.

Does a reference copy the String?​

No. It's an address of the existing value, so lending a large String costs no copy.

Conclusion​

Put & before a parameter type to borrow instead of taking ownership, and & before the argument to lend it. Use &mut when the function has to change the value, and keep using the value afterwards in either case.

Additional Resources​