如何在泛型上添加约束

时间:2014-10-14 11:11:52

标签: generics rust

我试图在Rust中实现OneToMany关系。这实现为几个HashMap s。

我很难找到如何限制OneToMany结构的泛型类型。似乎O和M都需要实现core::cmp::Eqcollections::hash::Hash特征。我一直无法在文档中找到所需的语法。

struct OneToMany<O,M> { 
  manyByOne: HashMap<O,Vec<M>>,
  oneByMany: HashMap<M,O>
}

impl<O,M> OneToMany<O,M> {
  fn new(one: O, many: M) -> OneToMany<O,M> {
    OneToMany {
      manyByOne: HashMap::new(),
      oneByMany: HashMap::new(),
    }
  }
}

编译器错误是:

$ cargo build
   Compiling chat v0.1.0 (file:///home/chris/rust/chat)
src/chat.rs:45:18: 45:30 error: the trait `core::cmp::Eq` is not implemented for the type `O`
src/chat.rs:45       manyByOne: HashMap::new(),
                                ^~~~~~~~~~~~
src/chat.rs:45:18: 45:30 note: the trait `core::cmp::Eq` must be implemented because it is required by `std::collections::hashmap::map::HashMap<K, V, RandomSipHasher>::new`
src/chat.rs:45       manyByOne: HashMap::new(),
                                ^~~~~~~~~~~~
src/chat.rs:45:18: 45:30 error: the trait `collections::hash::Hash` is not implemented for the type `O`
src/chat.rs:45       manyByOne: HashMap::new(),
                                ^~~~~~~~~~~~
src/chat.rs:45:18: 45:30 note: the trait `collections::hash::Hash` must be implemented because it is required by `std::collections::hashmap::map::HashMap<K, V, RandomSipHasher>::new`
src/chat.rs:45       manyByOne: HashMap::new(),
                                ^~~~~~~~~~~~
src/chat.rs:46:18: 46:30 error: the trait `core::cmp::Eq` is not implemented for the type `M`
src/chat.rs:46       oneByMany: HashMap::new(),
                                ^~~~~~~~~~~~
src/chat.rs:46:18: 46:30 note: the trait `core::cmp::Eq` must be implemented because it is required by `std::collections::hashmap::map::HashMap<K, V, RandomSipHasher>::new`
src/chat.rs:46       oneByMany: HashMap::new(),
                                ^~~~~~~~~~~~
src/chat.rs:46:18: 46:30 error: the trait `collections::hash::Hash` is not implemented for the type `M`
src/chat.rs:46       oneByMany: HashMap::new(),
                                ^~~~~~~~~~~~
src/chat.rs:46:18: 46:30 note: the trait `collections::hash::Hash` must be implemented because it is required by `std::collections::hashmap::map::HashMap<K, V, RandomSipHasher>::new`
src/chat.rs:46       oneByMany: HashMap::new(),
                                ^~~~~~~~~~~~
error: aborting due to 4 previous errors
Could not compile `chat`.

我在哪里可以在O和M上添加约束?

1 个答案:

答案 0 :(得分:4)

您可以在impl上添加约束:

impl<O: Eq + Hash, M: Eq + Hash> OneToMany<O,M>

或者,使用新的“where”语法

impl<O, M> OneToMany<O,M> where O: Eq + Hash, M: Eq + Hash

您可以参考the Guide's section on Traits了解有关约束的更多背景信息。