包含 Box 作为成员变量的结构:
type Item = dyn Fn() -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
struct Inner {
pub data: Box<Item>,
}
// a function, like the type: Item
fn parse() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
println!("parse called");
Ok(())
}
现在出现了自定义实现反序列化以使结构反Inner
序列化的问题:
let s = r#"{"data": "parse"}"#;
进入结构内部:
{
data: Box::new(parse)
}
我知道serde
不实现反序列Box<T>
化,并且必须手动实现反序列化,这是我的代码遵循文档给出的示例:
use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};
use std::fmt;
type Item = dyn Fn() -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
struct Inner {
pub data: Box<Item>,
}
fn parse() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
println!("parse called");
Ok(())
}
impl<'de> Deserialize<'de> for Inner {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
enum Field {
Data,
};
impl<'de> Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
where
D: Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`data` only")
}
fn visit_str<E>(self, value: &str) -> Result<Field, E>
where
E: de::Error,
{
match value {
"data" => Ok(Field::Data),
_ => Err(de::Error::unknown_field(value, FIELDS)),
}
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct InnerVisitor;
impl<'de> Visitor<'de> for InnerVisitor {
type Value = Inner;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("struct Inner")
}
fn visit_map<V>(self, mut map: V) -> Result<Inner, V::Error>
where
V: MapAccess<'de>,
{
let mut data = None;
while let Some(key) = map.next_key()? {
match key {
Field::Data => {
if data.is_some() {
return Err(de::Error::duplicate_field("data"));
}
data = Some(map.next_value()?);
}
}
}
let data = data.ok_or_else(|| de::Error::missing_field("data"))?;
//
// do something on the `data` and finally return a Item-like function (***)
//
Ok(Inner {
data: Box::new(parse),
}) // (***)
}
}
const FIELDS: &'static [&'static str] = &["data"];
deserializer.deserialize_struct("Inner", FIELDS, InnerVisitor)
}
}
fn main() {
let s = r#"{"data": "parse"}"#;
let inner: Inner = serde_json::from_str(s).unwrap();
}
但是,当我运行这些代码时,会出现错误:
Compiling playground v0.0.1 (/playground)
warning: unused variable: `inner`
--> src/main.rs:93:9
|
93 | let inner: Inner = serde_json::from_str(s).unwrap();
| ^^^^^ help: if this is intentional, prefix it with an underscore: `_inner`
|
= note: `#[warn(unused_variables)]` on by default
warning: unused variable: `data`
--> src/main.rs:76:21
|
76 | let data = data.ok_or_else(|| de::Error::missing_field("data"))?;
| ^^^^ help: if this is intentional, prefix it with an underscore: `_data`
warning: 2 warnings emitted
Finished dev [unoptimized + debuginfo] target(s) in 1.12s
Running `target/debug/playground`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("invalid type: string \"parse\", expected unit", line: 1, column: 16)', src/main.rs:93:48
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
粗略地说,我猜问题(***)
出在街区,但不知道如何解决。如何正确实施Deserialize
我的用例?