Rust 和 C 之间存在一些差异,这些差异没有显示在您在问题中引用的表中。
-
在铁锈中,可变性是绑定的属性而不是类型的属性 https://stackoverflow.com/a/59715542/1411457.
-
Rust 有严格的别名规则,因此您不能同时对任何变量有多个可变引用。
您的问题(简化)是:为什么我不能对可变变量有一个非可变引用,并通过它来改变该变量。但是,如果您可以这样做,您还可以有两个可用于修改变量的引用,如下所示:
let mut x = 10;
let x1 = &mut x;
let x2 = &x1; // Non mutable reference to x1, ok
let x3 = &x1; // Another non mutable reference to x1, ok
**x2 = 20; // uhoh, now I can mutate 'x' via two references ... !
**x3 = 30;
关于你的 C 相当于给定的 Rust 代码 - 你还没有根据表格翻译它。考虑一下:
let x2 = &x1;
从您引用的答案中的表格中:
a: &T == const T* const a; // Can't modify either
在这种情况下,T 将是const int*
。所以,它会是:
const int* const* const x2 = &x1;
你的整个程序将是:
int main() {
// let mut x = 10;
int x = 10;
// let x1 = &mut x;
// a: &mut T == T* const a with T=int
int* const x1 = &x;
// let x2 = &x1;
// a: &T == const T* const a with T = int* const
const int* const* const x2 = (const int* const* const) &x1;
// let x3 = &x2;
// a: &T == const T* const a with T = const int* const* const
const const int* const* const* const x3 = &x2;
***x3 = 20;
return 0;
}
请注意,需要进行强制转换以避免在分配 x2 时出现警告。这是一条重要的线索:我们正在有效地向指向的对象添加常量性。
如果你尝试编译你会得到:
t.c: In function ‘main’:
t.c:17:11: error: assignment of read-only location ‘***x3’
***x3 = 20;
^