References
References let you pass a way to access a value to a function without copying the value. &identifier is a reference to the identifier value, &Person is a type that is a reference to the Person type. To go from a reference to the value dereference let bob = *bob_ref, but this happens automatically with 'autoderef'.
References are stack allocated pointers to values in the heap. They represent a borrowed value.
#![allow(unused)] fn main() { let a = 1; let referenceToA: &i32 = &a; let mutableReferenceToA = &mut a; }
Dereferencing
* is the inverse of &.
#![allow(unused)] fn main() { let a = 1; let a_ref = &a; let b = *a_ref; }
The 'dot' operator
.dereferences automatically.
Mutable References
#![allow(unused)] fn main() { let mut identifier = 1; let mut_ref = &mut identifier; // this is a mutable reference. Mutable borrow. }
There can be only one mutable reference, and it cannot be in scope with an immutable reference.
More on passing to functions and mutability
fn function_name(variable: String)takes a String and owns it. If it doesn't return anything, then the variable dies inside the function.fn function_name(variable: &String)borrows a String and can look at itfn function_name(variable: &mut String)borrows a String and can change it