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

后端 未结 1 754
既然无缘
既然无缘 2021-01-29 04:23

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 rewrit

相关标签:
1条回答
  • 2021-01-29 05:01

    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?

    0 讨论(0)
提交回复
热议问题