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