为什么使用可变变量,使其寿命与不可变引用重叠,但我不能以相同的方式使用可变引用?

问题描述 投票:1回答:1

我不明白为什么借位检查器允许可变变量的生存期与不可变引用的生存期重叠,但是不允许可变引用的生存期与不可变引用的生存期重叠一生。

此编译:

let mut s = String::from("hello"); // some warning about s not needing to be mutable
let r = &s;
println!("{}, {}", r, s);

但这不是:

let mut s = String::from("hello");
let r_mut = &mut s; // mutable borrow here
let r = &s; // immutable borrow here
println!("{}, and {}", r, r_mut); // mutable borrow used here, error

为什么我可以使用可变变量以不可变的方式,使其寿命与不可变引用重叠,但是我不能使用可变引用以相同的不可变方式

variables rust reference immutability borrow-checker
1个回答
0
投票
scope
© www.soinside.com 2019 - 2024. All rights reserved.