3
녹에서 OneToMany 관계를 구현하려고합니다. 이것은 HashMap
두 쌍으로 구현됩니다.제네릭에 제약 조건을 추가하는 방법
OneToMany 구조체의 제네릭 형식을 제한하는 방법을 찾는 데 문제가 있습니다. O와 M은 모두 core::cmp::Eq
과 collections::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에 제약 조건을 추가 할 수 있습니까?
the impl. 'impl OneToMany '또는 새로운 "where"문법으로 impl OneToMany O : Eq + Hash, M : Eq + Hash' –
@PaoloFalabella 많은 감사 , 그것은 효과가 있었다. 당신이 당신의 코멘트를 대답한다면, 나는 그것을 받아 들일 것입니다. – fadedbee