4

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
jeanpaul62
  • 9,451
  • 13
  • 54
  • 94

1 Answers1

6

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?

jeanpaul62
  • 9,451
  • 13
  • 54
  • 94
  • 2
    If using a crate is also an option, [serde_with](https://crates.io/crates/serde_with) offers `display_fromstr` which uses the Display implementation for serialization and the FromStr implementation for deserialization. – Daniel Hauck Mar 09 '20 at 22:05