【发布时间】:2020-09-07 04:48:03
【问题描述】:
谁能解释为什么下面的代码会编译,但是如果我注释掉一行,那么即使代码本质上是做同样的事情,它也不会编译?
struct OtherStruct {
x: i32,
}
struct Inner {
blah: i32,
vector: Vec<OtherStruct>
}
struct Outer {
inner: Inner,
}
impl Inner {
pub fn set_blah(&mut self, new_val : i32) {
self.blah = new_val;
}
}
fn main() {
let mut outer = Outer {
inner: Inner {
blah: 10,
vector: vec![
OtherStruct { x: 1 },
OtherStruct { x: 2 },
OtherStruct { x: 3 },
OtherStruct { x: 4 },
OtherStruct { x: 5 },
]
}
};
for item in outer.inner.vector.iter() {
println!("{}", item.x);
outer.inner.blah = 4;
//outer.inner.set_blah(6);
}
}
编译错误是:
|
34 | for item in outer.inner.vector.iter() {
| -------------------------
| |
| immutable borrow occurs here
| immutable borrow later used here
...
37 | outer.inner.set_blah(6);
| ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
这对我来说很有意义,我想我想知道为什么当我不使用函数调用时允许我逃脱它,肯定会出现同样的可变性问题?
【问题讨论】:
-
来自 Niko Matsakis 的非常相关的博文:After NLL: Interprocedural conflicts