References
Like C++, Rust has references:
1. fn main() {
2. let mut x: i32 = 10;
3. let ref_x: &mut i32 = &mut x;
4. *ref_x = 20;
5. println!("x: {x}");
6. }
Some notes:
- We must dereference
ref_xwhen 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
mutcan be bound to different values over their lifetime.
Key points:
- Be sure to note the difference between
let mut ref_x: &i32andlet 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.
