O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Borrowing

As you saw before, moving ownership when making function calls does not usually make much sense. Instead, you can define the function parameters as borrowed references with the ampersand &. We can fix the previous code example to pass the compiler without cloning like this:

// functions-with-borrows-1.rs fn take_the_n(n: &u8) { } fn take_the_s(s: &String) { } fn main() {     let n = 5;     let s = String::from("string");     take_the_n(&n);     take_the_s(&s);     println!("n is {}", n);     println!("s is {}", s); } 

Note that the & needs be used in both the call site and in the parameter list. Similar to how variable bindings are by default, references are immutable by default.

In order to get to the actual value that's behind the reference, you ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required