0

Conceptually, I'd like to have an "extended" HashMap class that I'll call a FrequencyTable

#[derive(Clone)]
pub struct FrequencyTable<K,V>(HashMap<K,HashSet<V>>);

I'd like to define a "default" that goes over the HashMap member.

My first attempt was

impl<K,V> std::iter::IntoIterator for FrequencyTable<K,V> {
    type Item = (K,HashSet<V>);
    type IntoIter = std::collections::hash_map::Iter<'static, K, HashSet<V>>;

    fn into_iter(self) -> std::collections::hash_map::Iter<'static, K, HashSet<V>> {
        self.0.iter()
    }
}

which complains because K and V need lifetime bounds so I tried

impl<K,V> std::iter::IntoIterator for FrequencyTable<K,V> where K: 'static, V:'static {
    type Item = (K,HashSet<V>);
    type IntoIter = std::collections::hash_map::Iter<'static, K, HashSet<V>>;

    fn into_iter(self) -> std::collections::hash_map::Iter<'static, K, HashSet<V>> {
        self.0.iter()
    }
}

which then says expected parameter 'k', found '&K' ... But adding &s to the variables didn't solve the error.

financial_physician
  • 1,672
  • 1
  • 14
  • 34

1 Answers1

3

You need to use IntoIterator::into_iter not Iter::iter from the inner sources:

use std::collections::HashSet;
use std::collections::HashMap;

#[derive(Clone)]
pub struct FrequencyTable<K,V>(HashMap<K,HashSet<V>>);

impl<K,V> std::iter::IntoIterator for FrequencyTable<K,V> {
    type Item = (K,HashSet<V>);
    type IntoIter = std::collections::hash_map::IntoIter<K, HashSet<V>>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

Playground

Notice that Iter yields &T and takes &self, while IntoIter yields T and takes self. So you don't need to deal with the lifetimes for this IntoIter implementation.

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • what we need https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=807d10734ca80d4df1c9ecc3f480c7db – Stargateur Mar 15 '22 at 17:37
  • @Stargateur had no clue it was in nightly already! oh boy, that is exciting indeed :) – Netwave Mar 15 '22 at 21:11