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

标签 struct rust

我需要为我的 Herd 结构实现 rustc_serialize::Decoder 特性:

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,
            })
        })
    }
}

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

error[E0277]: the trait bound chrono::NaiveDate: rustc_serialize::Decodable is not satisfied

我正在努力手动实现 Decodable,这就是您在上面的代码中看到的内容。 NaiveDate from the rust-chrono crate是一个结构,其中一个字段的数据类型为 i32

当我现在运行代码时,我收到消息:

field ymdf of struct chrono::NaiveDate is private

如何为 NaiveDate 实现 Decoder?有没有更简单的方法来为我的 Herd 结构实现 Decodable?我是一个全能的初级程序员;也许还有另一种方式来看待这个问题。

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

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

最佳答案

NaiveDate 确实实现了 Decodable 但在可选功能 “rustc-serialize” 下。

您应该将此添加到您的 Cargo.toml 中以激活它:

chrono = { version = "0.2", features = ["rustc-serialize"]}

关于struct - 如何为字段值为另一个结构的结构实现 rustc_serialize::Decodable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40163538/

相关文章:

c++ - 关于C++结构和数组的一些问题

rust - 仅用于借用检查的零宽度引用?

intellij-idea - 如何自动修复 Rust 中未使用的导入?

c - 将数组中的值分配给结构数组

c - 初始化位域

rust - 我可以使用 Bincode 反序列化具有可变长度前缀的向量吗?

asynchronous - 初始化传递给异步代码(例如 tokio 和 hyper)的 Rust 变量

rust - 如何避免使用 IntoParallelIterator 绑定(bind)的可变和不可变借用

C : Vec of structures

c - 如何以指针格式访问结构内的数组?