I know that a Rust reference is much like a C pointer, and I think of Rust references as C pointers all the time. After some experiments and searching, I'm confused.
I'm familiar with C and I've read What's the difference between placing “mut” before a variable name and after the “:”?, which gives the following table:
// Rust C/C++ a: &T == const T* const a; // can't mutate either mut a: &T == const T* a; // can't mutate what is pointed to a: &mut T == T* const a; // can't mutate pointer mut a: &mut T == T* a; // can mutate both
The post is upvoted so I assume that it is correct.
I wrote the following Rust code
fn main() {
let mut x = 10;
let x1 = &mut x;
let x2 = &x1;
let x3 = &x2;
***x3 = 20;
}
in the hope that it is equivalent to the following C code
int main() {
int x = 10;
int *const x1 = &x;
int *const *const x2 = &x1;
int *const *const *const x3 = &x2;
***x3 = 20;
return 0;
}
The Rust code doesn't compile:
error[E0594]: cannot assign to `***x3` which is behind a `&` reference
--> src/main.rs:6:5
|
6 | ***x3 = 20;
| ^^^^^^^^^^ cannot assign
What's wrong here?
Strangely enough, the following code compiles!
fn main() {
let mut x = 10;
let mut x1 = &mut x;
let mut x2 = &mut x1;
let mut x3 = &mut x2;
***x3 = 20;
}
Why should let mut x1/2/3
be used instead of just let x1/2/3
? I think of let x1 = &mut x
as a constant pointer pointing to a mutable variable x
, but it doesn't seem to be right in Rust. Is that Stack Overflow post inaccurate or I misunderstand it?