如何使用现有的Display trait实施来实现序列化? [英] How can I implement Serialize using an existing Display trait implementation?
本文介绍了如何使用现有的Display trait实施来实现序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望在外部包装箱中的类型上实现Serialize
特质,但这是禁止的.我看了serde的远程派生,但是似乎很多工作都在重写类型.
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.
对于我来说,我希望序列化的所有类型都实现Display
特征,而对于序列化,我只想使用该特征.
In my case, all the types I wish to serialize implement the Display
trait, and for serialization, I just want to use that trait.
我该怎么做?
推荐答案
这是我的尝试(注意:我是OP):
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)
}
但是也许有更简单的方法可以做到这一点?
But there's maybe a more straightforward way of doing this?
这篇关于如何使用现有的Display trait实施来实现序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文