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

Collect duplicate fields using derive attribute #1859

Closed
Plecra opened this issue Jul 17, 2020 · 2 comments
Closed

Collect duplicate fields using derive attribute #1859

Plecra opened this issue Jul 17, 2020 · 2 comments

Comments

@Plecra
Copy link

Plecra commented Jul 17, 2020

This continues #690. @dtolnay recommended using a Deserializer adapter as a solution, but I'm not sure how it helps. I don't think there's any Deserialize method that could be used for this behaviour.

#[derive(Deserialize)]
struct Cores {
    #[serde(duplicates)]
    core: Vec<String>,
}

Here's an possible implementation on the playground

@nickbabcock
Copy link

Yeah I ended up implementing this with my own custom derive macro for structs (based on your gist -- thank you again for showing me)

Some implementation detail differences in behavior when a field is decorated with #[serde(duplicated)] compared to a regular field:

  • Initialized with Vec::new() (ie: not initialized to an std::option::Option::None)
  • When the __Field is encountered, always blindly push the next value:
(#name).push(::serde::de::MapAccess::next_value::<#farg>(&mut __map)?);
  • No need to have a step to extract field from an Option or check if there is a default fallback for said field.

There are some significant downsides to implementing one's own custom derive macro -- I haven't implemented many of serde's field / container attributes. I've also only gotten duplicated to work for the Vec containers. So if there does exist a Deserializer adapter for a solution, I'd love to see it!

@dtolnay
Copy link
Member

dtolnay commented Jan 23, 2022

I still don't feel this is something that needs to be built into the serde crate. Thanks anyway for the suggestion!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

3 participants