首页 文章

在HashMap上实现一个使用带边界的方法的特征

提问于
浏览
0

我想在HashMaps上实现以下特征:

trait IdAssigner<K, V> {
    // If key has already been seen, returns (id_for_key, false). Otherwise
    // assigns a new id_for_key (starting with 0 and increasing) and returns
    // (id_for_key, true).
    fn assign_id(mut self, key: K) -> (V, bool);
}

impl<K, V> IdAssigner<K, V> for HashMap<K, V> where 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() as V;
            self[&key] = id;
            (id, true)
        }
    }
}

编译器给出了我想在HashMap的实现中调用的方法的各种错误 . 我怀疑我需要在我的impl语句中添加相同的边界,这些边界存在于这些方法中 . 我该如何修复此代码?

Playground

1 回答

  • 1

    错误:找不到类型名为contains_key的方法

    正如您在contains_key的文档中看到的那样,定义了 contains_keyimpl 块具有边界 where K: Eq + Hash, S: HashState . 将K的绑定添加到where子句也将修复其他 no method 错误和 cannot index a value of type std :: collections :: hash :: map :: HashMap`错误 .

    之后你会得到

    错误:非标量演员:usize as V

    对应于这一行:

    let id = self.len() as V;
    

    你在这里要做的是将 usize 转换为 V 实例化的任何类型 . 这通常不起作用,因为 V 实际上可能是与 usize (例如 Vec 或任何其他结构)不兼容的东西 . 因为你真正想要的是从某个键到id的 HashMap ,你可以简单地删除所有 V 泛型并直接设置 HashMap 的Value参数:

    trait IdAssigner<K> {
        fn assign_id(mut self, key: K) -> (usize, bool);
    }
    
    impl<K> IdAssigner<K> for HashMap<K, usize>
        where K: Eq + Hash,
    

相关问题