I have a structure that contains two fields, and I want to change one field (mutable borrowing) using another field (immutable borrowing), but I get an error message from a borrower check.
For example, the following code:
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); }
gives the following error:
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
What are the ways Rust can update one field using another from a closure?
source share