jeanpaul62
jeanpaul62

Reputation: 10571

How can I implement Serialize using an existing Display trait implementation?

I wish to implement the Serialize trait on a type in an extern crate, but it's forbidden. I had a look at serde's remote derive, but it seems a lot of work rewriting the types.

In my case, all the types I wish to serialize implement the Display trait, and for serialization, I just want to use that trait.

How would I do that?

Upvotes: 6

Views: 2684

Answers (1)

jeanpaul62
jeanpaul62

Reputation: 10571

Here's my try (note: I'm the OP):

use serde::{Serialize, Serializer};
use std::io::Error;
use std::fmt::Display;

#[derive(Debug, Serialize)]
pub enum MyError {
    Custom,
    #[serde(serialize_with = "use_display")]
    Io(Error)
}

fn use_display<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
    T: Display,
    S: Serializer
{
    serializer.collect_str(value)
}

playground

But there's maybe a more straightforward way of doing this?

Upvotes: 10

Related Questions