References
A reference &T is a non-owning pointer the compiler proves is valid for its lifetime. You create one with &value and dereference with * or autoderef.
Detailed Explanation
&T is a shared reference. It is a pointer, usually one word for a sized T, two words for a slice or trait object. You may copy a &T — copying a reference is Copy even when T is not. You may not write through it. There is no null &T in safe Rust. If you need absence, Option<&T>, which is still one word for many T thanks to niche optimisation.
Autoderef means session.user_id works when session is Session, &Session, Box<Session>, or &&Session. The compiler inserts * as needed. * on a reference is the explicit dereference: let n = *r when r is &i32. You cannot move out of a reference unless T is Copy: *s where s is &String would steal the string from the owner.
References are not C++ references in every way, but they are closer to C++ references than to C pointers: they must be valid, they are not nullable, and they do not own. They are not Box. Dropping a reference does not drop T.
Lifetimes are part of the type. &'a T is a reference that lives at most 'a. Most of the time you do not write 'a because elision fills it in. You write it when returning a reference or storing one in a struct.
When you write &T: read without owning. When you write &mut T: exclusive write. When you write *const T: FFI or unsafe, and you are on your own for validity.
Shared references to !Sync types cannot cross threads, even though &T is Copy. The Copy of a reference is a second pointer on the same thread. That distinction is why people confuse "I copied the reference" with "I can send it". Sending requires T: Sync. Copying requires nothing of T except that the reference is live.
Code Examples
fn len(name: &String) -> usize {
name.len() // autoderef to str
}
fn main() {
let name = String::from("ada");
let r = &name;
println!("{} {}", len(&name), r); // prints: 3 ada
let n = 4;
let rn = &n;
println!("{}", *rn); // prints: 4
}Common Gotchas
You cannot move out of a shared reference
`*r` where `r: &String` does not give you a `String`. Clone, or take ownership of the original.
`&T` is `Copy`
Passing a reference around does not consume it. The owner still owns `T`.
A reference in a struct needs a lifetime
`struct Line<'a> { text: &'a str }` cannot outlive `text`. Store a `String` if the struct must own the text.
Prefer `&str` over `&String`
The slice form accepts literals and substrings. `String` derefs to `str`.