2

I'm trying to serialize the following Result object, however I'm getting an error because while it workings for some of the properties, it doesn't seem to work on path, even though all of the elements involved have 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, although I can't get it to pull in the Rocket crate, it must not be one of the 100 most popular.

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`

From my understanding, #[derive(Serialize)] should automatically create a serialize method which serde can then use. However I would expect it to work for the properties too. Do I need to create structs for all the types and then derive Serialize for all of those structs?

Do I need to do something to enable it?

The following crates are in use:

rocket = "*" 
serde = { version = "1.0", features = ["derive"] } 
rocket_contrib = "*"
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Craig Harley
  • 304
  • 5
  • 18

1 Answers1

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

This means that Rc does not implement Serialize. See How do I serialize or deserialize an Arc<T> in Serde?. TL;DR:

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

Once adding that, the error message changes to:

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`

That's because every type that needs to be serialized must implement Serialize:

#[derive(Serialize)]
struct GraphNode {
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366