简体   繁体   English

使用rustc_serialize反序列化JSON对象:为什么我需要实现PartialEq?

[英]Deserialising JSON object with rustc_serialize: why do I need to implement PartialEq?

I have a file containing a JSON object with unknown keys. 我有一个包含未知密钥的JSON对象的文件。 I would like to decode this object into a structure but don't understand how to declare this structure. 我想将此对象解码为一个结构,但不了解如何声明此结构。

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());

The following error occurs: 发生以下错误:

error: the trait `core::cmp::PartialEq` is not implemented for the type `MyStruct` [E0277]
    let j: BTreeMap<String, MyStruct> = json::decode(&raw_json).unwrap();
                                        ^~~~~~~~~~~~

Would I have to implement Decodable for MyStruct myself then? 我是否必须DecodableMyStruct实施Decodable

json::decode is defined as: json::decode定义为:

pub fn decode<T: Decodable>(s: &str) -> DecodeResult<T>

This means that given a string slice, it will attempt to be decoded into a type specified by the user, so long as that type implements Decodable . 这意味着给定一个字符串切片,它将尝试解码为用户指定的类型,只要该类型实现Decodable On the page for Decodable , you can see all the implementations of it, including the one for BTreeMap : Decodable页面上,您可以看到它的所有实现,包括BTreeMap

impl<K: Decodable + PartialEq + Ord,
     V: Decodable + PartialEq>
Decodable for BTreeMap<K, V>

This shows that in order to decode to a BTreeMap , both the key and value in the map need to be PartialEq . 这表明为了解码到BTreeMap ,地图中的键和值都需要是PartialEq However, I wasn't clear on why that is actually needed. 但是,我不清楚为什么实际需要它。 BTreeMap should only require that the key is Ord and not care about the value at all. BTreeMap应该只要求密钥是Ord而根本不关心该值。 To that end, I've opened a pull request to remove those bounds, and it was accepted! 为此,我打开了拉取请求以删除这些边界,并且它被接受了! ^_^ I guess that means that the bounds might have just been a typo originally. ^ _ ^我猜这意味着边界本来可能只是一个错字。

@Shepmaster提示的简单答案是要么实现PartialEq特性要么导出它,因为错误消息表明:

#[derive(RustcDecodable, PartialEq, Debug)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM