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

feat(derive): add custom field for struct #2563

Closed

Conversation

saiintbrisson
Copy link

@saiintbrisson saiintbrisson commented Aug 8, 2023

Hi! It is not infrequently that I find myself needing to compute a custom
field that is only present on serialization and is calculated off of another
one of the struct's fields. Usually, I'll either implement Serialize myself,
but this gets tiring if the struct is too large and is prone to errors, or create
another struct with the field I want just before serializing.

I hereby propose creating a new container attribute field that allows for
the creation of fields on the go at the moment of serialization:

#[derive(Serialize)]
#[serde(
    field(name = "b", getter = "Self::b_getter"),
    field(name = "c", with = "c_serialize_with")
)]
struct CustomFields {
    a: i32
}

impl CustomFields {
    fn b_getter(&self) -> i32 {
        self.a * 2
    }
}

fn c_serialize_with<S: Serializer>(v: &CustomFields, ser: S) -> Result<S::Ok, S::Error> {
    (v.a * 3).serialize(ser)
}

So a CustomFields { a: 10 } results in:

{
  "a": 10,
  "b": 20,
  "c": 30
}

I'm still not happy with the attributes' names, it may make more sense to
call it serialize_field or something along those lines?

Copy link
Member

@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 for the PR.

This was previously discussed and rejected in #760.

@dtolnay dtolnay closed this Aug 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants