Skip to content

Add Fields::iter_member#1716

Merged
dtolnay merged 2 commits intodtolnay:masterfrom
Fancyflame:master
Aug 11, 2024
Merged

Add Fields::iter_member#1716
dtolnay merged 2 commits intodtolnay:masterfrom
Fancyflame:master

Conversation

@Fancyflame
Copy link
Copy Markdown
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
Comment thread src/data.rs
/// 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
Copy Markdown
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
Copy Markdown
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
Copy Markdown
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
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