简体   繁体   English

Rust 参考书中的问题

[英]Issues in the Rust reference book

https://doc.rust-lang.org/reference/types/closure.html#capture-modes 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.相反,如果闭包直接使用 self.vec,那么它将尝试通过可变引用来捕获 self。 But since self.set is already borrowed to iterate over, the code would not compile.但是由于 self.set 已经被借用来迭代,代码将无法编译。

The reference book says the code would not compile.参考书说代码不会编译。 , but the code can be compiled. ,但代码可以编译。 So why?所以为什么?

This was true in the past, but has changed since and the reference was not updated.过去确实如此,但此后发生了变化,并且参考未更新。 Since edition 2021, closures capture disjoint fields .自 2021 版以来, 闭包捕获不相交的字段

See reference issue #1066 .请参阅参考问题 #1066

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM