We interchange one field of the structure when borrowing another in closing

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?

+5
source share
1 answer

Typically, the borrower verification tool can distinguish between different fields of the structure, but this does not work within the closure (lambdas).

Instead, borrow the second field outside the closure:

 let field2 = &strct.field2; strct.field1.retain(|v| !field2.contains(v)); 
+11
source

Source: https://habr.com/ru/post/1246319/


All Articles