我有一个包含带有未知键的JSON对象的文件。我想将这个对象解码成一个结构,但不知道如何声明这个结构。发生使用rustc_serialize反序列化JSON对象:为什么需要实现PartialEq?
extern crate rustc_serialize;
use rustc_serialize::json;
use std::collections::BTreeMap;
#[derive(RustcDecodable, Debug)]
struct MyStruct {
foo: u8,
bar: Vec<String>,
}
let raw_json = r#"{
"A": {
"foo": 2,
"bar": ["a", "b"],
},
"C": {
"foo": 1,
"bar": ["c", "d"],
},
:
}"#;
let j: BTreeMap<String, MyStruct> = json::decode(&raw_json).unwrap();
println!("{:?}", j.get("A").unwrap());
以下错误:
error: the trait `core::cmp::PartialEq` is not implemented for the type `MyStruct` [E0277]
let j: BTreeMap<String, MyStruct> = json::decode(&raw_json).unwrap();
^~~~~~~~~~~~
我将不得不实施Decodable
为MyStruct
自己呢?
您是否试图按错误消息的建议实施PartialEq? – Shepmaster
不,tbh。我认为这个错误是不正确的,因为这个结构等式应该可能派生。我现在实施了'PartialEq',它工作。但是,我仍然不明白为什么我需要这样做。网上的例子似乎都没有做到这一点。 – Kreisquadratur
*对于这个结构相等应该可能派生* - 没有特征会自动派生,这就是为什么你必须添加'#[derive]'。 – Shepmaster