rust Serde序列化程序示例包含错误

pu82cl6c  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(99)

我正在尝试使用serde创建自定义序列化程序。我将代码复制并粘贴到:https://serde.rs/impl-serializer.html
我唯一改变的是我没有使用error::Result,而是使用anyhow::Resulterror::Result不存在,这就是原因。
我得到的错误是trait objects must include thedynkeyword。因此,我所做的是转到type Error = Error;的所有示例,并将其替换为type Error = dyn Error;
这样做,我得到了更多的错误。我得到the size for values of typedyn error::Errorcannot be known at compilation time、``dyn error::Errorcannot be shared between threads safelythe size for values of type(dyn error::Error + 'static)cannot be known at compilation timemismatched types
我想,为了摆脱最后一个错误,我可以只做Result<Self::Ok, Self::Error>,摆脱顶部的use anyhow::Result;
这是其他错误,我不知道如何摆脱的问题。我是Rust的新手,我只是不确定在这种情况下应该做什么。

e4eetjau

e4eetjau1#

查看implementation of serde_json是定义自定义序列化器的一个很好的参考。
在提供的自定义序列化程序示例中,它只是使用use error::{Error, Result};作为任何序列化错误的占位符,它们实际上并不存在。
你应该做的是为你的序列化器定义你自己的错误类型,可能使用thiserror crate,并删除任何dyn标记,因为错误现在是一个具体的类型。
例如:

#[derive(Debug, thiserror::Error)]
#[error("My custom serializer error: {0}")]
pub struct Error(String);

pub type Result<T> = core::result::Result<T, Error>;

impl ser::Error for Error {
    fn custom<T>(msg: T) -> Self where T: Display {
        Error(msg.to_string())
    }
}

...

字符串

相关问题