Hi everyone,
I came across the capture modes
of the Closure types
in the Rust Reference and I took the example from the docs, changed the commented lines a bit, and used it in a simple example to better understand what's going on.
use std::collections::HashSet;
#[derive(Debug)]
struct SetVec {
set: HashSet<u32>,
vec: Vec<u32>
}
impl SetVec {
fn populate(&mut self) {
// let vec = &mut self.vec;
self.set.iter().for_each(|&n| {
self.vec.push(n); // use `vec` to compile successfully
})
}
}
// My code example
fn main() {
let mut set_vec = SetVec {
set: [1,2,3].iter().cloned().collect(),
vec: vec![]
};
set_vec.populate();
println!("set_vec = {:?}", set_vec);
}
The code above does not compile because I use self
inside the closure as in self.vec.push(n)
. This tells the closure that it should fully capture self
.
The way I understand it is that the Rust compiler is complaining about this situation:
-
self.set
is an immutable shared-borrow : read-only (because of the iterator) -
self
is a mutable borrow : exclusive to closure (because of theself.vec.push(n)
)
Is my understanding correct ?
Thank you!