I came from C++, and try to understand what Rust reference is. According to my current understanding, I think Rust reference is more close to C++ pointer, is that right?
You can see:
&T can be converted into const T* safely
Trying to modify the value of a binding through a mut ref, you need to write:
let mut a=1;
{
let b = &mut a;
*b = 5;
}
i.e., use * to convert a reference to a value (which is same for pointer in C++).
struct Ccc{
x:i32,
y:i32
}
fn main() {
let a=Ccc{x:1,y:2};
let b=&a;
println!("{}", (*b).x);//the star can also be omitted.
}
When trying to access a member of a struct through ref, you can write:
b.x
or
(*b).x
Is the underlying mechanism that rust will insert * when one trying to access the member through a ref?
Forget about comparing references to pointers. It will make you struggle with the borrow checker.
Think of Rust references as read/write locks for objects in memory that give a temporary permission to access something.
In C it's usual to use lots of pointers for basically anything, but in Rust using many references may get quite cumbersome or not even pass the borrow checker.
In C it's normal to allocate and return something as a pointer, but in Rust that kind of pointer doesn't even have a syntax! For example, Box is a pointer, and Rc, String and Vec are used in the same places where you'd use a pointer in C, despite being neither a pointer nor a reference.