HashMap是否可以接受多种类型或任何类型的值?

时间:2020-01-29 18:47:03

标签: rust hashmap

我有一个基于this playground的实现,但是,一旦我插入一个键/值对,似乎就锁定了键/值对的类型。

虽然我至少要接受多种类型的值,但我想同时接受任何类型的键和值。

错误:

error[E0308]: mismatched types
  --> src/main.rs:28:18
   |
28 |     cc.insert(2, 3);
   |                  ^ expected &str, found integer
   |
   = note: expected type `&str`
              found type `{integer}`

代码:

use std::cmp::Eq;
use std::collections::hash_map::Keys;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;

trait ComponentContainer<'a, K: 'a> {
    type Iter: Iterator<Item = &'a K>;
    fn keys(&'a self) -> Self::Iter;
}

impl<'a, V: 'a, K: 'a + Hash + Eq> ComponentContainer<'a, K> for HashMap<K, V> {
    type Iter = Keys<'a, K, V>;
    fn keys(&'a self) -> Keys<'a, K, V> {
        self.keys()
    }
}

fn print_keys<'a, K: 'a + Debug, C: ComponentContainer<'a, K>>(cc: &'a C) {
    for k in cc.keys() {
        println!("{:?}", k);
    }
}

fn main() {
    let mut cc = HashMap::new();
    cc.insert(1, "foo");
    cc.insert(2, 3);
    print_keys(&cc);
}

0 个答案:

没有答案
相关问题