如何为外部类型实现 serde 的序列化和反序列化特征?

Way*_*oke 12 rust serde

我正在尝试实现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))
    }
}
Run Code Online (Sandbox Code Playgroud)

KeybdKey来自inputbot板条箱。

And*_*sen 4

正确的方法是使用Newtype模式。通过将外部类型包装在 a 中Newtype,您可以为其实现特征。

您的示例将适用于以下内容:

#[derive(Serialize, Deserialize)]
pub struct ImageBinds {
    binds: HashMap<MyKeybdKey, Vec<u8>>,
}

// This is a Newtype containing the external type .
struct MyKeybdKey(KeybdKey);

impl Serialize for MyKeybdKey {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_u64(u64::from(self.0))
    }
}

impl<'de> Deserialize<'de> for MyKeybdKey {
    fn deserialize<D: Deserializer>(deserializer: D) -> Result<Self, D::Error> {
        // ...deserialize implementation.
    }
}
Run Code Online (Sandbox Code Playgroud)

我没有填写实现Deserialize,因为它会相当长,但基本概念是在实现中反转From您所依赖的实现Serialize