gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:26:06 24 4
gpt4 key购买 nike

我知道 Rust 引用很像 C 指针,而且我一直认为 Rust 引用是 C 指针。经过一些实验和搜索,我很困惑。
我熟悉 C 并且我读过 What's the difference between placing “mut” before a variable name and after the “:”? ,它给出了下表:

// 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 之间存在一些差异,这些差异未显示在您在问题中引用的表格中。

  • 在 Rust 中,mutability is a property of the binding rather than of the type .
  • 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;

    关于与给定 Rust 代码等效的 C - 你没有根据表格翻译它。考虑一下:
    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;
    ^

    关于rust - 关于引用的可变性和引用所指值的可变性的一些混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64002601/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com