Skip to content

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

Closed as not planned
@Prashant-Shekhar-Rao

Description

@Prashant-Shekhar-Rao

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions