当我为任何数据格式编写序列化程序时,我可以选择为更复杂的类型分离序列化程序。
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(())
}
...
}
我该怎么办?
1条答案
按热度按时间eiee3dmh1#
您可以在
MyStructSerializer
中引用序列化器: