In the code below (playground), I want to return an iterator for a vector contained in a hashmap as a value for a given key.
It feels inefficient to clone the vector before obtaining the iterator but, without the cloning, I get a compile error, which I do not understand
Is there a way to avoid cloning, keep the function signature, and still work around the compile error?
// code from playground
use std::collections::{HashMap};
use std::hash::Hash;
fn get_iterator<'a, K, V>(map: &HashMap<&'a K, Vec<&'a V>>, key: &K) -> Option<impl Iterator<Item=&'a V>>
where V: 'a,
K: Eq + Hash {
match map.get(&key) {
None => { None }
Some(vec) => {
let it = vec.clone().into_iter();
Some(it)
}
}
}
confused thinking
I guess that I assume that an iterator over a vector of references &T will dereference the elements to T before adding its own reference again to get &T but that this does not happen resulting in &&T.
However, it appears that cloning somewhat implements this process while I would have guessed that cloning retains the type?
dispensable attempt
I tried to change the type of the hashmap but this gave me eventually problems elsewhere in my code where I create these HashMaps since I create the stored vecs incrementally requiring mutable vecs and these then require HashMap<&'a K, &'a mut Vec<&'a V>>
but then I do not know how to fix the following get_iterator
function for that change again.
use std::collections::{HashMap};
use std::hash::Hash;
fn get_iterator<'a, K, V>(map: &HashMap<&'a K, &'a Vec<&'a V>>, key: &K) -> Option<impl Iterator<Item=&'a V>>
where V: 'a,
K: Eq + PartialEq + Hash,
V: Eq + PartialEq + Hash {
match map.get(&key) {
None => { panic!("unknown key") }
Some(vec) => {
let it = vec.into_iter().map(|x|*x);
Some(it)
}
}
}