Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

types/closure is not accurate. We don't need to use a new variable when capturing a field from a struct #1412

Closed
Prashant-Shekhar-Rao opened this issue Oct 2, 2023 · 1 comment

Comments

@Prashant-Shekhar-Rao
Copy link

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

@Prashant-Shekhar-Rao Prashant-Shekhar-Rao changed the title https://doc.rust-lang.org/reference/types/closure.html is not accurate types/closure is not accurate. We don't need to use a new variable when capturing a field from a struct Oct 2, 2023
@ehuss
Copy link
Contributor

ehuss commented Oct 2, 2023

Thanks for the report! The reference hasn't been updated for the 2021 Edition closure capturing. It is being worked on in #1059, but I haven't had a chance to finish it off. You can find more up-to-date documentation at https://doc.rust-lang.org/edition-guide/rust-2021/disjoint-capture-in-closures.html.

Closing as a duplicate of #1066.

@ehuss ehuss closed this as not planned Won't fix, can't repro, duplicate, stale Oct 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants