我正在为serde编写一个自定义序列化器.
为此,我还需要一个自定义错误类型.
Serde要求我为此实现serde::ser::Error
.
serde::ser::Error
反过来又要求我实现一个custom()
方法,其中参数只受std::fmt::Display
trait绑定的限制.
所以我想到了这个:
use std::fmt::{Debug, Display, Formatter};
#[derive(Debug)]
pub enum Error {
Custom(Box<dyn Display>),
CannotSerializeMap,
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Custom(error) => Display::fmt(error, f),
Self::CannotSerializeMap => write!(f, "cannot serialize map"),
}
}
}
impl std::error::Error for Error {}
impl serde::ser::Error for Error {
fn custom<T>(msg: T) -> Self
where
T: Display,
{
Self::Custom(Box::new(msg))
}
}
然而,我不能推导出Debug
,这是std::error::Error
所必需的,而std::error::Error
又是serde::ser::Error
所必需的,因为Box<dyn Display>
并不实现Debug
.
我不能为它实现Debug
,因为Box
和trait Debug
本身都不在我的crate中.
我也不能在custom()
中为T
添加适当的约束,因为这会 destruct trait的契约.
我怎么才能解决这个问题?