1

I'm working on the iterator adaptor which uses a HashMap internally. First, it matches all the input iterator keys with the map and flags them as matched. At the end I want to iterate over the map's values flagged as not matched.

Apparently, I need to store both the map and its Values iterator (which stores the state of the iteration) in the same struct, but I cannot figure out how to do it.

Here is an example without matching the input iterator to keep things simple:

use std::collections::hash_map::{HashMap, Values,};
use std::hash::Hash;

struct Foo<'a, K, V>
    where K: 'a + Hash + Eq,
          V: 'a + Clone,
{
    map: HashMap<K, (V, bool)>,
    values: Values<'a, K, (V, bool)>,
}

impl<'a, K, V> Foo<'a, K, V>
    where K: 'a + Hash + Eq,
          V: 'a + Clone,
{
    fn new<I>(it: I) -> Self
        where I: Iterator<Item=(K, V)>
    {
        // load the HashMap
        let mut map: HashMap<K, (V, bool)> = HashMap::new();
        for (k, v) in it {
            map.insert(k, (v, false));
        }
        // I cannot use `let values = map.values();` since map will be moved to Foo.
        Foo {map: map, values: ???}
    }
}

impl<'a, K, V> Iterator for Foo<'a, K, V>
    where K: 'a + Hash + Eq,
          V: 'a + Clone,
{
    type Item = V;
    fn next(&mut self) -> Option<Self::Item> {
        match self.values.next() {
            loop {
                match some.values.next() {
                    Some(v) if !v.1 => return Some(Clone::clone(&v.0)),
                    Some(_) => continue,
                    None => return None,
                }
            }
        }
    }
}

fn main() {
    let it = (0..).zip("AB".chars());
    let foo = Foo::new(it);
    for v in foo {
        println!("{}", v);
    }
}

Thanks a lot for any suggestions.

milancio
  • 91
  • 5
  • You can't. This is likely a duplicate of http://stackoverflow.com/q/31825650/155423 or http://stackoverflow.com/q/31794503/155423 or http://stackoverflow.com/q/20698384/155423 or http://stackoverflow.com/q/30823880/155423 or http://stackoverflow.com/q/25269597/155423. – Shepmaster Aug 13 '15 at 13:06
  • 1
    Ah, ok. At least now I'm sure it cannot be done that way:) Thanks for your help. – milancio Aug 13 '15 at 13:21
  • No worries. I might suggest asking another question about how to do what you are trying to do. I believe there is a way to do it. You can reference this question as one attempt of solving the problem. – Shepmaster Aug 13 '15 at 13:23

0 Answers0