0

I have an implementation based off this playground, however, once I insert a key/value pair, that seems to lock in the type of key/value pairs.

Optimally, I would like to accept both keys and values of any type, although, at the very least I need to accept values of multiple types.

Error:

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}`

Code:

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);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

0 Answers0