i have following trait want implement on hashmaps:
trait idassigner<k, v> { // if key has been seen, returns (id_for_key, false). otherwise // assigns new id_for_key (starting 0 , increasing) , returns // (id_for_key, true). fn assign_id(mut self, key: k) -> (v, bool); } impl<k, v> idassigner<k, v> hashmap<k, v> v: add<v> { fn assign_id(mut self, key: k) -> (v, bool) { if self.contains_key(&key) { (self[&key], false) } else { let id = self.len() v; self[&key] = id; (id, true) } } } the compiler gives various errors methods want call in implementation on hashmap don't exist. suspect need add same bounds impl statement exist on methods. how fix code?
error: no method named
contains_keyfound type
as can see in documentation of contains_key, impl block in contains_key defined, has bounds where k: eq + hash, s: hashstate. adding bound k clause fix other no method errors , cannot index value of typestd::collections::hash::map::hashmap` error.
after get
error: non-scalar cast:
usizev
which corresponds line:
let id = self.len() v; what trying here cast usize whatever type v instanciated to. can't work in general, v might not compatible usize (e.g. vec or other struct). since want hashmap key id, can remove v generics , directly set value parameter of hashmap:
trait idassigner<k> { fn assign_id(mut self, key: k) -> (usize, bool); } impl<k> idassigner<k> hashmap<k, usize> k: eq + hash,
Comments
Post a Comment