You cannot save the Values iterator because it contains references to the HashMap . These links may become invalid if you move the map. However, you can use the HashMap with the into_iter method. It owns all the HashMap values and can be moved to a new structure.
Here is the setup of your code from an earlier question. This is not a connection left or right. There is the difficulty of switching from one iterator to the completion of another iterator.
use std::collections::hash_map::{HashMap, IntoIter}; use std::hash::Hash; struct Foo<K, V> where K: Hash + Eq, V: Clone, { iter: IntoIter<K, (V, bool)>, } impl<K, V> Foo<K, V> where K: Hash + Eq, V: Clone, { fn new<I>(it: I) -> Self where I: Iterator<Item=(K, V)> { let mut map = HashMap::new(); for (k, v) in it { map.insert(k, (v, false)); } Foo { iter: map.into_iter() } } } impl<K, V> Iterator for Foo<K, V> where K: Hash + Eq, V: Clone, { type Item = V; fn next(&mut self) -> Option<Self::Item> { loop { match self.iter.next() { Some((_, (v, false))) => return Some(v.clone()), Some(_) => continue, None => return None, } } } } fn main() { let it = (0..).zip("AB".chars()); let foo = Foo::new(it); for v in foo { println!("{}", v); } }
However, you do not need to do anything to get what you want. You can simply create a hash map and check it out when you iterate over another item. I accidentally created a left outer join, but just flipped the arguments to get the right outer join. ^ _ ^
use std::collections::hash_map::HashMap; use std::hash::Hash; struct LeftOuterJoin<L, K, RV> { left: L, right: HashMap<K, RV>, } impl<L, K, RV> LeftOuterJoin<L, K, RV> where K: Hash + Eq { fn new<LI, RI>(left: LI, right: RI) -> Self where L: Iterator<Item=LI::Item>, LI: IntoIterator<IntoIter=L>, RI: IntoIterator<Item=(K, RV)> { LeftOuterJoin { left: left.into_iter(), right: right.into_iter().collect() } } } impl<L, K, LV, RV> Iterator for LeftOuterJoin<L, K, RV> where L: Iterator<Item=(K, LV)>, K: Hash + Eq, RV: Clone { type Item = (K, LV, Option<RV>); fn next(&mut self) -> Option<Self::Item> { match self.left.next() { Some((k, lv)) => { let rv = self.right.get(&k); Some((k, lv, rv.cloned())) }, None => None, } } } fn main() { let mut left = HashMap::new(); left.insert(1, "Alice"); left.insert(2, "Bob"); let mut right = HashMap::new(); right.insert(1, "Programmer"); for (id, name, job) in LeftOuterJoin::new(left.into_iter(), right) { println!("{} ({}) is a {:?}", name, id, job); } }