我需要为我的 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/