6

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?

0

1 Answer 1

10

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?

Sign up to request clarification or add additional context in comments.

1 Comment

If using a crate is also an option, serde_with offers display_fromstr which uses the Display implementation for serialization and the FromStr implementation for deserialization.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.