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

impl Serializer for &mut fmt::Formatter #1705

Merged
merged 1 commit into from May 10, 2020

Conversation

jethrogb
Copy link

@jethrogb jethrogb commented Jan 3, 2020

Allow using &mut fmt::Formatter as a serializer for primitive types.

One use-case I have in mind in particular is implementing Display for enums that also implement Serialize.

If you believe this impl should exist, due to coherence, this crate is the only place it could exist.

@dtolnay
Copy link
Member

dtolnay commented Jan 3, 2020

Thanks! Could you give an example of how this could be used?

@jethrogb
Copy link
Author

jethrogb commented Jan 3, 2020

#[derive(Serialize)]
#[serde(rename_all="kebab-case")]
enum MessageType {
    StartRequest,
    EndRequest,
}

impl fmt::Display for MessageType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.serialize(f)
    }
}

@jethrogb jethrogb requested a review from dtolnay February 5, 2020 12:43
@peterjoel
Copy link

This is actually a nice idea. I frequently end up with a dev dependency on serde_json, just to do a string comparison with a serialised value. This could be very convenient.

It doesn't actually need to implement Serializer for Formatter though; a new struct could delegate for the purpose, and live in a separate crate. It could also be implemented as a macro that generates a Display or Debug impl, without the need for an extra type.

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.

Looks good; I am on board with providing this impl.

It looks like this doesn't yet work in the no-std build (https://travis-ci.org/github/serde-rs/serde/jobs/632277218) but I will follow up separately with a fix.

I will also add your example usage in a doc comment.

@dtolnay dtolnay merged commit 726ff5e into serde-rs:master May 10, 2020
@dtolnay
Copy link
Member

dtolnay commented May 10, 2020

Published in 1.0.108.

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.

None yet

3 participants