关于引用的可变性和引用所指的值的可变性的一些混淆

2024-04-06

我知道 Rust 引用很像 C 指针,并且我一直将 Rust 引用视为 C 指针。经过一些实验和搜索后,我很困惑。

我熟悉 C 并且我读过将“mut”放在变量名之前和“:”之后有什么区别? https://stackoverflow.com/a/29682542/155423,给出下表:

// 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

该帖子已被投票,因此我认为它是正确的。

我写了下面的 Rust 代码

fn main() {
    let mut x = 10;
    let x1 = &mut x;
    let x2 = &x1;
    let x3 = &x2;
    ***x3 = 20;
}

希望它等价于下面的C代码

int main() {
    int x = 10;
    int *const x1 = &x;
    int *const *const x2 = &x1;
    int *const *const *const x3 = &x2;
    ***x3 = 20;
    return 0;
}

Rust 代码无法编译:

error[E0594]: cannot assign to `***x3` which is behind a `&` reference
 --> src/main.rs:6:5
  |
6 |     ***x3 = 20;
  |     ^^^^^^^^^^ cannot assign

这是怎么回事?

奇怪的是,下面的代码可以编译!

fn main() {
    let mut x = 10;
    let mut x1 = &mut x;
    let mut x2 = &mut x1;
    let mut x3 = &mut x2;
    ***x3 = 20;
}

为什么要let mut x1/2/3被使用而不是仅仅let x1/2/3?我想let x1 = &mut x作为指向可变变量的常量指针x,但在 Rust 中似乎不太正确。那个 Stack Overflow 帖子不准确还是我误解了?


Rust 和 C 之间存在一些差异,这些差异没有显示在您在问题中引用的表中。

  1. 在铁锈中,可变性是绑定的属性而不是类型的属性 https://stackoverflow.com/a/59715542/1411457.

  2. 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;
           ^
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

关于引用的可变性和引用所指的值的可变性的一些混淆 的相关文章

随机推荐