rust - 为什么你可以借用可变引用并仍然使用两者?

标签 rust lifetime rust-cargo borrow-checker borrowing

#[derive(Debug)]
struct Rect {
    width: u32,
    height: u32,
}

fn main() {
    let mut r = Rect { width: 30, height: 30 };
    let b = &mut r;
    let c: &Rect = b;
    println!("{:?},{:?}", b, c);
}

在代码中,b 是可变借用的,而 c 是不可变借用的,因此这不应编译,但可以编译并运行而不会出现任何错误。

最佳答案

this shouldn't compile

为什么?是的,b 可变地借用了 r。但是 c 永久地借用了 b,所以现在 b 是永久借用的,你无法改变它。

如果您尝试分配给 b 的任何字段,那么编译器将立即抛出错误。

let mut r = Rect { width: 30, height: 30 };
let b = &mut r;
let c: &Rect = b;

// This assignment will fail, as yes, `b` is a
// mutable reference but it is immutably borrowed.
b.width = 40;

println!("{:?},{:?}", b, c);

该示例与将 b 全部删除相同。即使 r 是可变的,您仍然无法改变 r

let mut r = Rect { width: 30, height: 30 };
let c: &Rect = &r;

// This assignment will fail for the same reason,
// `r` is a mutable reference but it is immutably borrowed.
r.width = 40;

println!("{:?},{:?}", r, c);

关于rust - 为什么你可以借用可变引用并仍然使用两者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65438330/

相关文章:

php - mysql_connect 连接生命周期

rust - `:` 中的 `?` 和 `{:?}` 是什么意思

generics - 算术运算的 Rust 泛型

rust - 即使显式也无法推断值类型

rust - 如何在 `macro_rules!` 中声明一个变量?

c++ - 当一个数组由子表达式创建时,其中的临时变量会发生什么?

android - 单击搜索按钮时将关闭不可取消的对话框

rust - 运行 "ld: library not found for -liconv"时应该如何解决 "cargo build"错误?

rust - 可执行文件实际上需要目标目录中的哪些文件?

rust - 如何使用不同版本的 Rust 编译器构建依赖关系?