Implement function for both HashMap<K, V> and BTreeMap<K, V>

I'm quite new to rust, and have been messing around for about 4 days now. I have code which is pretty much identical, and I can't seem to figure out how to make them one impl block. Below the two impl blocks are listed.

impl<K: Display, V: Display> StringTable for HashMap<K, V> {
    fn to_table(&self) -> Vec<String> {
        let mut values = vec![[String::from("Keys:"), String::from("Values:")]];

        for (key, value) in self {
            values.push([format!("{}", key), format!("{}", value)]);
        }

        generate_string_grid(&values)
    }
}

impl<K: Display, V: Display> StringTable for BTreeMap<K, V> {
    fn to_table(&self) -> Vec<String> {
        let mut values = vec![[String::from("Keys:"), String::from("Values:")]];

        for (key, value) in self {
            values.push([format!("{}", key), format!("{}", value)]);
        }

        generate_string_grid(&values)
    }
}

Any help would be appreciated, thanks :slight_smile:

You may be looking for IntoIterator in std::iter - Rust , which both BTreeMap and HashMap implements, since all you really need appears to be the ability to get an iterator over (K, V).

I was looking at that, however both HashMap and BTreeMap implement different IntoIter structs, so while I assume I can do:

... StringTable for dyn IntoIterator<Item = (K, V), ____ >

I'm not too sure what I would put in the blank

Something like:

impl<I, K: Display, V: Display> StringTable for I
where
    for<'a> &'a I: IntoIterator<Item = (&'a K, &'a V)>,
{
...
}
5 Likes

For example. (I also replaced Display with ToString.)

2 Likes

Thanks a million, that works out!