gpt4 book ai didi

rust - 序列化结构上的子属性似乎不起作用

转载 作者:行者123 更新时间:2023-11-29 08:05:53 25 4
gpt4 key购买 nike

我正在尝试序列化以下 Result 对象,但出现错误,因为虽然它适用于某些属性,但它似乎不适用于 path ,即使所有涉及的元素都有 implementations provided by Serde .

#[macro_use]
extern crate serde;
extern crate rocket;

use rocket_contrib::json::Json;
use std::rc::Rc;

#[derive(Serialize)]
struct Result {
success: bool,
path: Vec<Rc<GraphNode>>,
visited_count: u32,
}
struct GraphNode {
value: u32,
parent: Option<Rc<GraphNode>>,
}

fn main(){}

fn index() -> Json<Result> {
Json(Result {
success: true,
path: vec![],
visited_count: 1,
})
}

Playground ,虽然我不能让它拉进火箭箱,但它一定不是最受欢迎的 100 个之一。

error[E0277]: the trait bound `std::rc::Rc<GraphNode>: serde::Serialize` is not satisfied
--> src/main.rs:11:5
|
11 | path: Vec<Rc<GraphNode>>,
| ^^^^ the trait `serde::Serialize` is not implemented for `std::rc::Rc<GraphNode>`
|
= note: required because of the requirements on the impl of `serde::Serialize` for `std::vec::Vec<std::rc::Rc<GraphNode>>`
= note: required by `serde::ser::SerializeStruct::serialize_field`

根据我的理解,#[derive(Serialize)] 应该会自动创建一个 serde 可以使用的序列化方法。但是我希望它也适用于这些属性。我是否需要为所有类型创建结构,然后为所有这些结构派生 Serialize

我需要做些什么来启用它吗?

以下 crate 正在使用中:

rocket = "*" 
serde = { version = "1.0", features = ["derive"] }
rocket_contrib = "*"

最佳答案

the trait bound `std::rc::Rc<GraphNode>: serde::Serialize` is not satisfied

这意味着 Rc 实现Serialize。参见 How do I serialize or deserialize an Arc<T> in Serde? .长话短说:

serde = { version = "1.0", features = ["derive", "rc"] }

添加后,错误消息变为:

error[E0277]: the trait bound `GraphNode: serde::Serialize` is not satisfied
--> src/main.rs:11:5
|
11 | path: Vec<Rc<GraphNode>>,
| ^^^^ the trait `serde::Serialize` is not implemented for `GraphNode`
|
= note: required because of the requirements on the impl of `serde::Serialize` for `std::rc::Rc<GraphNode>`
= note: required because of the requirements on the impl of `serde::Serialize` for `std::vec::Vec<std::rc::Rc<GraphNode>>`
= note: required by `serde::ser::SerializeStruct::serialize_field`

那是因为每个需要序列化的类型都必须实现Serialize:

#[derive(Serialize)]
struct GraphNode {

关于rust - 序列化结构上的子属性似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54913013/

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