rust 在对结构使用单独的序列化程序时如何访问主序列化程序

m4pnthwp  于 2023-03-02  发布在  其他
关注(0)|答案(1)|浏览(136)

当我为任何数据格式编写序列化程序时,我可以选择为更复杂的类型分离序列化程序。

pub struct Serializer {
    output: String,
}

impl<'a> ser::Serializer for &'a mut Serializer {
     type Ok = ();
     type Error = Error;

     type SerializeStruct = MyStructSerializer; // separate Serializer for structs

     ...
}

如果我采用这种方法,并且需要在复杂类型的序列化程序中序列化基本类型,则需要调用serialize()并引用主序列化程序,而主序列化程序在那里不可用。

pub struct MyStructSerializer {
}

impl<'a> ser::SerializeStructVariant for &'a mut MyStructSerializer {
    type Ok = Value;
    type Error = Error;

    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
    where
        T: ?Sized + Serialize,
    {
        key.serialize(&mut **self)?; // Need reference to Serializer here
        value.serialize(&mut **self)?; // Need reference to Serializer here
        Ok(())
    }
    ...
}

我该怎么办?

eiee3dmh

eiee3dmh1#

您可以在MyStructSerializer中引用序列化器:

pub struct MyStructSerializer<'a> {
    serializer: &'a mut Serializer,
}

impl<'a> ser::Serializer for &'a mut Serializer {
    type Ok = ();
    type Error = Error;

    type SerializeStruct = MyStructSerializer<'a>; // separate Serializer for structs

    // ...

    fn serialize_struct_variant(
        self,
        name: &'static str,
        variant_index: u32,
        variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error>
    {
        MyStructSerializer { serializer: self }
    }
    // ...
}

相关问题