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

时间:2019-02-27 19:23:10

标签: rust serde

我正在尝试序列化以下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

我需要做些事情来启用它吗?

正在使用以下板条箱:

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

1 个答案:

答案 0 :(得分:2)

  
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?。 TL; DR:

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 {