Like C++, Rust has references:
fn main() {
let mut x: i32 = 10;
let ref_x: &mut i32 = &mut x;
*ref_x = 20;
println!("x: {x}");
}
x: 20
notes:
- We must dereference ref_x when assigning to it, similar to C and C++ pointers.
- Rust will auto-dereference in some cases, in particular when invoking methods (try ref_x.count_ones()).
- References that are declared as mut can be bound to different values over their lifetime.
- Be sure to note the difference between let mut ref_x: &i32 and let ref_x: &mut i32. The first one represents a mutable reference which can be bound to different values, while the second represents a reference to a mutable value.
Dangling References
Rust will statically forbid dangling references:
fn main() {
let ref_x: &i32;
{
let x: i32 = 10;
ref_x = &x;
}
println!("ref_x: {ref_x}");
}
Compiling playground v0.0.1 (/playground)
error[E0597]: `x` does not live long enough
--> src/main.rs:5:17
|
4 | let x: i32 = 10;
| - binding `x` declared here
5 | ref_x = &x;
| ^^ borrowed value does not live long enough
6 | }
| - `x` dropped here while still borrowed
7 | println!("ref_x: {ref_x}");
| ------- borrow later used here
For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` (bin "playground") due to previous error
- A reference is said to “borrow” the value it refers to.
- Rust is tracking the lifetimes of all references to ensure they live long enough.
- We will talk more about borrowing when we get to ownership.