我正在尝试为一个外部枚举实现Serialize
和Deserialize
,但我不知道该怎么做。它有From<u64>
,所以我只想让这个对象用那个来序列化。
#[derive(Serialize, Deserialize)]
pub struct ImageBinds {
binds: HashMap<KeybdKey, Vec<u8>>, // KeybdKey doesn't implement serialize
}
// won't compile with this:
// only traits defined in the current crate can be implemented for arbitrary types
// impl doesn't use only types from inside the current crate
// I understand the orphan rule and all that but I have no idea how else I'd implement it
// I've looked at serde remote stuff and I cannot work out how to do it with an enum without
// literally just copying the whole crate into my scope which is stupid
impl Serialize for KeybdKey {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_u64(u64::from(*self))
}
}
KeybdKey
来自于 inputbot
包。
HashMap
中,远程推导功能将无法帮助你。你可以使用自定义反序列化HashMap
(即with
属性),一个包装类型或者尝试serde_with
箱来解决此问题。文档中只提到了From<KeybdKey> for u64
,但没有From<u64>
。因此,这样只能让您编写序列化代码,但不能进行反序列化。 - jonasbb