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

Add Fields::iter_member #1716

Merged
merged 2 commits into from
Aug 11, 2024
Merged

Add Fields::iter_member #1716

merged 2 commits into from
Aug 11, 2024

Conversation

Fancyflame
Copy link
Contributor

Acts like Fields::iter, but map its Field items to Member.

For instance, in this struct

struct Foo {
    a: f32,
    b: bool
}

We use iter_member to access its fields, and implement Clone for it.

let fields: Fields = ...;
let idents = fields.iter().map(|f| &f.ident);
let members = fields.iter_member();
quote! {
    impl Clone for Foo {
        fn clone(&self) -> Self {
            Self {
                #(#idents: self.#members.clone(),)*
            }
        }
    }
}

Then it generates

impl Clone for Foo {
    fn clone(&self) -> Self {
        Self {
            a: self.a.clone(),
            b: self.b.clone(),
        }
    }
}

There is a similar effect on unnamed fields in which iterates Member::Index instead.

the span of unnamed field member will fallback to `Span::call_site` if `Spanned` trait is not available
/// An iterator over the fields of a struct or variant as [`Member`]s.
#[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
#[derive(Clone)]
pub struct IterMember<'a> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this type should be publicly accessible ... so probably don't put it in its own private module

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have also considered this issue before, but I noticed that many iterator function s under Generics also return private types. What do you think?

Copy link
Owner

@dtolnay dtolnay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@dtolnay dtolnay merged commit 8b68c06 into dtolnay:master Aug 11, 2024
18 checks passed
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

Successfully merging this pull request may close these issues.

3 participants