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.