A reference lets you look at a value without taking ownership of it. Write `&` before a value to create one: `let number_ref = &number;`. Think of it as an address that leads to the value, rather than a second copy of the value. section 2.1 section 2.11
This is especially useful with functions. Passing a `String` by value moves ownership into the function; trying to pass it again produces a “use of moved value” error. Passing `&country` to a parameter of type `&String` lets the function read it while `country` remains the owner. section 2.7
fn print_country(country_name: &String) {
println!("{}", country_name);
}
fn main() {
let country = String::from("Austria");
print_country(&country); #1
print_country(&country);
}
The function takes a `&String`, so it can print the same owned string on two calls without taking ownership. section 2.7
An ordinary reference is immutable: it can view data but not change it. You can have many immutable references to the same value. To change a value through a reference, use `&mut`; while a mutable reference is in use, you cannot also have another mutable or immutable reference to that value. section 2.5.1 section 2.5
fn main() {
let mut my_number = 8;
let num_ref = &mut my_number;
*num_ref += 10; #1
println!("{}", my_number);
let second_number = 800;
let triple_reference = &&&second_number;
println!("Are they equal? {}", second_number == ***triple_reference);
}
Here `*num_ref += 10` changes the number behind a mutable reference. The `*` operator is called dereferencing; it reaches the value that `&` references. section 2.5
A reference also needs its value to remain available. If a function creates a `String` locally, it cannot return a reference to that string: the string is cleaned up when the function ends. Returning the owned `String` is possible instead. section 2.4 section 10.2.1
error[E0515]: cannot return value referencing local variable country --> src/main.rs:4:5 | 3 | let country_ref = &country; | -------- `country` is borrowed here 4 | country_ref | ^^^^^^^^^^^ returns a value referencing data owned by the current function
The compiler points to the local value being borrowed and explains why returning that reference is not allowed. section 2.4
You will also meet references in string types. A `String` owns its data; a `&str` is a borrowed string slice, or view into string data. When a function only needs to read owned data, an immutable reference is usually the simplest choice and avoids cloning it. section 2.2 section 2.8
















