如何为具有另一个结构的字段值的struct实现rustc_serialize :: Decodable?

Hun*_*ter 1 struct rust

我需要rustc_serialize::Decoder为我的Herdstruct 实现trait :

extern crate chrono;
extern crate rustc_serialize;

use chrono::NaiveDate;
use rustc_serialize::Decodable;

struct Herd {
    id: i32,
    breed: String,
    name: String,
    purchase_date: NaiveDate,
}

impl Decodable for Herd {
    fn decode<D: Decoder>(d: &mut D) -> Result<Herd, D::Error> {
        d.read_struct("Herd", 4, |d| {
            let id = try!(d.read_struct_field("id", 0, |d| d.read_i32()));
            let breed = try!(d.read_struct_field("breed", 1, |d| d.read_str()));
            let name = try!(d.read_struct_field("name", 2, |d| d.read_str()));
            let purchase_date = try!(d.read_struct_field("purchase_date", 3, |i| {
                i.read_struct("NaiveDate", 1, |i| {
                    let ymdf = try!(i.read_struct_field("ymdf", 0, |i| i.read_i32()));
                    Ok(NaiveDate { ymdf: ymdf })
                })
            }));

            Ok(Herd {
                id: id,
                breed: breed,
                name: name,
                purchase_date: purchase_date,
            })
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

我无法使用,#[derive(RustcDecodable)]因为发生以下错误:

error[E0277]: the trait bound chrono::NaiveDate: rustc_serialize::Decodable is not satisfied
Run Code Online (Sandbox Code Playgroud)

我正在努力手动实现Decodable,这就是你在上面的代码中看到的.NaiveDate来自rust-chrono crate是一个带有一个数据类型字段的结构i32.

当我立即运行代码时,我收到消息:

struct chrono的字段ymdf :: NaiveDate是私有的

如何实现DecoderNaiveDate?有没有更简单的方法来实现Decodable我的Herd结构?我是一个全能的初学者程序员; 也许还有另一种方法来看待这个问题.

我正在使用具有以下依赖项的Rust 1.12:

  • nickel = "0.9.0"
  • postgres = { version = "0.12", features = ["with-chrono"]}
  • chrono = "0.2"
  • rustc-serialize = "0.3"

mca*_*ton 5

NaiveDate确实实现Decodable但在可选功能下"rustc-serialize".

您应该将其添加到您Cargo.toml的激活中:

chrono = { version = "0.2", features = ["rustc-serialize"]}
Run Code Online (Sandbox Code Playgroud)