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

Support flatten as a container attribute #2644

Closed
SpriteOvO opened this issue Nov 4, 2023 · 1 comment
Closed

Support flatten as a container attribute #2644

SpriteOvO opened this issue Nov 4, 2023 · 1 comment
Labels

Comments

@SpriteOvO
Copy link

Let's say I have a internal private struct struct P, and I also have multiple public structs

(All these structs are #[derive(Deserialize)], I omitted it from the code below)

struct P { ... }

struct A { p: P, ... }
struct B { p: P, ... }
struct C { p: P, ... }

Since P is a private struct, I want to hide the field p from the deserialization of these public structs, so we have to write the code in this way

struct P { ... }

struct A { #[serde(flatten)] p: P, ... }
struct B { #[serde(flatten)] p: P, ... }
struct C { #[serde(flatten)] p: P, ... }

#[serde(flatten)] is being written over and over again, considering that if there are a lot of such public structs, if we forget to write the field attr somewhere, it will expose this unintended field p to the user. This is hard to discover unless we write tests for each public struct.

So if we support flatten as a container attribute, we can get rid of that worry

#[serde(flatten)]
struct P { ... }

struct A { p: P, ... }
struct B { p: P, ... }
struct C { p: P, ... }
@dtolnay
Copy link
Member

dtolnay commented Nov 7, 2023

This is not something that can be implemented in most formats. By the time any code in P's Serialize impl runs, the field name "p" would already have been emitted. Similarly P's Deserialize impl would only come into play if a "p" field is present.

@dtolnay dtolnay closed this as completed Nov 7, 2023
@dtolnay dtolnay added the derive label Nov 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

2 participants