Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues in the Rust reference book

Tags:

rust

https://doc.rust-lang.org/reference/types/closure.html#capture-modes

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.

The reference book says the code would not compile. , but the code can be compiled. So why?

like image 366
wangliqiu2021 Avatar asked Aug 03 '26 11:08

wangliqiu2021


1 Answers

This was true in the past, but has changed since and the reference was not updated. Since edition 2021, closures capture disjoint fields.

See reference issue #1066.

like image 97
Chayim Friedman Avatar answered Aug 06 '26 03:08

Chayim Friedman