Reference in Rust
The heart of Rust!
1. What is References?
Instead of moving the ownership of a value to another variable or function, Rust allows you to borrow that value using a reference.
- A reference is a “view” to data, not real data.
- It is wrote by &.
- When pass reference in function, root value doesn’t lose ownership -> after function run completely, you still use the initial value.
func do_stuff(s: &String) {
println!("Got: {}", s);
}
func main() {
let s1 = String::from("hello");
do_stuff(&s1); // pass reference, s1 isn't moved.
println!("{}", s1); // still used
}2. How References Work “Under The Hood”?
When you create a reference like &s1 , Rust actually creates a pointer to the underlying data.
Get 0x48core’s stories in your inbox
Join Medium for free to get updates from this writer.
However, unlike C/C++, Rust doesn’t require you to manually deal with raw pointers because:
- References are always valid thanks to the lifetime system.
- There are no full references.
- The compiler ensures you cannot have a reference that outlives the original data.
3. Immutable vs Mutable reference
- By default, a reference is immutable: you cannot change the value through that reference.
- If you want to modify the value, you need to use a mutable reference:
&mut.
fn change(s: &mut String) {
s.push_str(" world"); // can change because of &mut
}
fn main() {
let mut s = String::from("hello");
change(&mut s);
println!("{}", s); // hello world
}4. Dereference
- A reference is similar to a pointer, so if you want to access the actual value, you need to deference it using
*. - However, when you use the dot syntax (like
s.len()ors.push_str()), Rust will automatically deference for you.
5. The Borrowing Rules (Reference Safety Rules)
Rust enforces an important rule to prevent race conditions and data corruption:
At any given time, you can have either:
- multiple immutable references (
&T) or - exactly one mutable reference (
&mut T)
You can’t have both at the same time!
fn main() {
let mut s = String::from("hello");
let r1 = &s;
let r2 = &mut s; // error: can't borrow mutable when having immutable
}6. References and Threads (Borrowing Rules in Multithreading)
These rules also apply in a multithreaded context:
- You can share multiple immutable references across many threads.
- But a mutable reference can only be used by one thread at a time — unless you use synchronization mechanism such as locks, Mutex, RwLock, etc.





