我正在尝试使用serde创建自定义序列化程序。我将代码复制并粘贴到:https://serde.rs/impl-serializer.html
我唯一改变的是我没有使用error::Result
,而是使用anyhow::Result
。error::Result
不存在,这就是原因。
我得到的错误是trait objects must include the
dynkeyword
。因此,我所做的是转到type Error = Error;
的所有示例,并将其替换为type Error = dyn Error;
这样做,我得到了更多的错误。我得到the size for values of type
dyn error::Errorcannot be known at compilation time
、``dyn error::Errorcannot be shared between threads safely
、the size for values of type
(dyn error::Error + 'static)cannot be known at compilation time
和mismatched types
。
我想,为了摆脱最后一个错误,我可以只做Result<Self::Ok, Self::Error>
,摆脱顶部的use anyhow::Result;
。
这是其他错误,我不知道如何摆脱的问题。我是Rust的新手,我只是不确定在这种情况下应该做什么。
1条答案
按热度按时间e4eetjau1#
查看implementation of serde_json是定义自定义序列化器的一个很好的参考。
在提供的自定义序列化程序示例中,它只是使用
use error::{Error, Result};
作为任何序列化错误的占位符,它们实际上并不存在。你应该做的是为你的序列化器定义你自己的错误类型,可能使用thiserror crate,并删除任何
dyn
标记,因为错误现在是一个具体的类型。例如:
字符串