5
我有一個包含兩個字段的結構體,我想用另一個字段(immutable borrow)修改一個字段(可變借用),但我從借用檢查器中得到一個錯誤。可變地借用一個結構體字段,同時借用另一個結合體
例如,下面的代碼:
struct Struct {
field1: Vec<i32>,
field2: Vec<i32>,
}
fn main() {
let mut strct = Struct {
field1: vec![1, 2, 3],
field2: vec![2, 3, 4],
};
strct.field1.retain(|v| !strct.field2.contains(v));
println!("{:?}", strct.field1);
}
提供了以下錯誤:
error[E0502]: cannot borrow `strct` as immutable because `strct.field1` is also borrowed as mutable
--> src/main.rs:12:25
|
12 | strct.field1.retain(|v| !strct.field2.contains(v));
| ------------ ^^^ ----- - mutable borrow ends here
| | | |
| | | borrow occurs due to use of `strct` in closure
| | immutable borrow occurs here
| mutable borrow occurs here
什麼是封閉內更新使用另一個領域的鏽的方法呢?
謝謝!我想知道爲什麼它在關閉中不起作用,但是...... –