即使我将其派生为结构,也无法使用parity_codec的Encode

时间:2019-06-25 20:24:08

标签: rust traits

我正尝试在具有派生实现的结构上使用Encode::encode,但出现此错误:

error[E0599]: no method named `encode` found for type `AnimalCollection<Animal>` in the current scope
  --> src/main.rs:42:57
   |
13 | struct AnimalCollection<A: AnimalTrait> {
   | --------------------------------------- method `encode` not found for this
...
42 |     println!("animal collection encoded = {:?}",animals.encode());
   |                                                         ^^^^^^
   |
   = note: the method `encode` exists but the following trait bounds were not satisfied:
           `AnimalCollection<Animal> : _IMPL_DECODE_FOR_Animal::_parity_codec::Encode`
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `encode`, perhaps you need to implement it:
           candidate #1: `_IMPL_DECODE_FOR_Animal::_parity_codec::Encode`

这是代码:

use indexmap::map::IndexMap;
use parity_codec;
use parity_codec::{Decode, Encode};

#[derive(Clone, PartialEq, Eq, Encode, Decode, Debug)]
struct Animal {
    name: String,
    cell: u32,
}

trait AnimalTrait: Encode + Decode {}

impl AnimalTrait for Animal {}

#[derive(Clone, PartialEq, Eq, Encode, Decode, Debug)]
struct AnimalCollection<A: AnimalTrait> {
    animals: IndexMap<String, A>,
}

impl<A: AnimalTrait> AnimalCollection<A> {
    fn new() -> AnimalCollection<A> {
        AnimalCollection {
            animals: IndexMap::new(),
        }
    }

    fn add(&mut self, name: String, a: A) {
        self.animals.insert(name, a);
    }
}

fn main() {
    let a = Animal {
        name: String::from("Tiger"),
        cell: 10,
    };
    println!("animal struct encoded = {:?}", a.encode());
    let mut animals = AnimalCollection::<Animal>::new();
    animals.add(
        String::from("Dog"),
        Animal {
            name: String::from("Dog"),
            cell: 1,
        },
    );
    animals.add(
        String::from("Cat"),
        Animal {
            name: String::from("Cat"),
            cell: 2,
        },
    );
    println!("animal collection encoded = {:?}", animals.encode());
}

即使我自动#[derive]去除了所有特征,为什么它仍然不起作用?我该如何解决?

由于我具有EncodeDecode特性,因此我不应该自己真正实现任何功能,还是应该实现?

我测试了这段代码,它可以在Animal结构上运行,但是不能在AnimalCollection结构上运行。我还尝试在Encode上实现AnimalCollection特质,但立即收到“冲突的实现”错误,因此我对如何解决这个问题颇感困惑。

Cargo.toml有点棘手,您需要使用derive功能:

[package]
name = "encmap"
version = "0.0.1"
edition = "2018"

[dependencies]
parity-codec = { version = "3.3", features = ["derive"] }
indexmap = "1.0.2"

0 个答案:

没有答案