This is my first encounter with Rust, and I am reading the chapter on vectors in the current version of the Rust Book. I do have previous experience with other languages (mostly functional ones, where the following issues are hidden).
Running the following code snippet (from the book) returns 3:
fn main() {
let v = vec![1, 2, 3, 4, 5];
let third: &i32 = &v[2];
println!("{}", third);
}
- The first thing that I do not understand is why the
thirdinside theprintln!macro isn't referenced. I would have expected the above code to print the memory address of the 3rd element ofv(as in C and C++), not its content.
Consider now the code (notice the reference this time inside println!):
fn main() {
let v = vec![1, 2, 3, 4, 5];
let third: &i32 = &v[2];
println!("{}", *third);
}
- Why does the code code above produce exactly the same output as the one above it, as if the
*made no difference?
Finally, let us rewrite the above code snippets eliminating references completely:
fn main() {
let v = vec![1, 2, 3, 4, 5];
let third: i32 = v[2];
println!("{}", third);
}
- Why does this last version produce the same output as the previous two? And what type does
v[2]really have: is it an&i32or ani32?
Are all of the above a manifestation of the automatic dereferencing that is only once alluded to in a previous chapter? (If so, then the book should be rewritten, because it is more confusing than clarifying.)