Reference in Rust vs. C++
March 20, 2024
Notes for the reference in rust
Switching to Rust from C++ would encounter this question: does the reference sematics in rust is same as the C++?, Let’s describe it with an example.
A quick example #
Here is an example of finding the largest value from a list of integers.
In Rust we can write like this:
fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let mut largest = &number_list[0];
for number in &number_list {
if number > largest {
largest = number;
}
}
println!("The largest number is {}, {}", largest, number_list[0]);
}
Where the let mut largest = &number_list[0];
takes the reference to the first element of the list. But the first number of the list is kept unchanged in the end.
However, if we write the code in the same way as C++:
#include <iostream>
#include <vector>
int main() {
auto number_list = std::vector<int>{34, 50, 100, 63};
auto &largest = number_list[0];
for (auto &item : number_list) {
if (item > largest) {
largest = item;
}
}
std::cout << largest << " " << number_list[0] << std::endl;
}
The result would be the largest
and number_list[0]
refer to the same memory address, and the first number of the list actually becomes 100
in the end.
Assigning reference #
In rust, Assigning a reference to a variable makes that variable point somewhere new:
let x = 10;
let y = 20;
let mut r = &x;
if b { r = &y; }
assert!(*r == 10 || *r == 20);
The reference r initially points to x. But if b is true, the code points it at y instead, as illustrated in Figure below:
This behavior may seem too obvious to be worth mentioning: of course r now points to y, since we stored &y in it. But we point this out because C++ references behave very differently: as shown earlier, assigning a value to a reference in C++ stores the value in its referent. Once a C++ reference has been initialized, there’s no way to make it point at anything else.