Closed as not planned
Closed as not planned
Description
Composite types such as structs, tuples, and enums are always captured entirely, not by individual fields. It may be necessary to borrow into a local variable in order to capture a single field:
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| {
vec.push(n);
})
}
}
If, instead, the closure were to use self.vec directly, then it would attempt to capture self by mutable reference. But since self.set is already borrowed to iterate over, the code would not compile.
This means that this code should not compile.
use std::collections::HashSet;
struct SetVec {
set: HashSet<u32>,
vec: Vec<u32>
}
impl SetVec {
fn populate(&mut self) {
self.set.iter().for_each(|&n| {
self.vec.push(n);
})
}
}
But this code compiles perfectly.
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=e739bcc43dc34f40ef07235f06c69f63
Metadata
Metadata
Assignees
Labels
No labels