gpt4 book ai didi

rust - 使用Box对结构进行反序列化

转载 作者:行者123 更新时间:2023-12-03 11:32:32 24 4
gpt4 key购买 nike

包含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(())
}
现在出现的问题是,自定义实现对struct Inner进行反序列化的反序列化:
let s = r#"{"data": "parse"}"#;
转换为struct内部:
{
data: Box::new(parse)
}
我知道 serde不会为 Box<T>实现反序列化,而必须手动实现Deserialize,这是我的代码,遵循 docmentaion给出的示例:
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

最佳答案

该警告提示您:您没有使用数据,因此Rust不在乎Option内的类型。其实我很惊讶它正在编译。由于使用serdes默认类型,Rust假定您期望(),而您期望String。根本不会消耗您的数据,所以只需执行以下操作:

let mut data: Option<&str> = None;
另外,我建议您将所有 Field实现替换为:
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum Field {
Data,
}
(由于未知原因,此堆栈在 playground上溢出,但是我希望这是操场上的问题)

另外,您可以只使用 deserialize_with:
use serde::{Deserialize, Deserializer};

type Item = dyn Fn() -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
#[derive(Deserialize)]
struct Inner {
#[serde(deserialize_with = "deserialize_data")]
pub data: Box<Item>,
}

fn deserialize_data<'de, D>(d: D) -> Result<Box<Item>, D::Error>
where
D: Deserializer<'de>,
{
let data = <&str>::deserialize(d)?;
println!("{}", data);
Ok(Box::new(parse))
}

fn parse() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
println!("parse called");
Ok(())
}

fn main() {
let s = r#"{"data": "parse"}"#;
let inner: Inner = serde_json::from_str(s).unwrap();
}
这是更好的方法,因为通过Serde宏实现比纯朴的实现要好得多。

关于rust - 使用Box对结构进行反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64780981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com