.into_iter().map(|(_, v)| v)
是惯用的方法。一点也不难看。
如果你愿意,你可以:
use std::collections::hash_map;
use std::collections::HashMap;
use std::iter::{ExactSizeIterator, FusedIterator};
struct IntoValues<K, V> {
iter: hash_map::IntoIter<K, V>,
}
impl<K, V> IntoValues<K, V> {
fn new(map: HashMap<K, V>) -> Self {
Self {
iter: map.into_iter(),
}
}
}
impl<K, V> Iterator for IntoValues<K, V> {
type Item = V;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(_, v)| v)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<K, V> ExactSizeIterator for IntoValues<K, V> {}
impl<K, V> FusedIterator for IntoValues<K, V> {}
trait HashMapTool {
type IntoValues;
type Item;
fn into_values(self) -> Self::IntoValues;
}
impl<K, V> HashMapTool for HashMap<K, V> {
type Item = V;
type IntoValues = IntoValues<K, V>;
fn into_values(self) -> Self::IntoValues {
IntoValues::new(self)
}
}
fn main() {
let mut h: HashMap<_, _> = HashMap::new();
h.insert(1, "foo".to_owned());
let _vals: Vec<_> = h.into_values().collect();
}