实现用于迭代其HashMap属性的struct的IntoIterator

时间:2016-02-28 15:05:31

标签: rust

我有一个类型为HashMap的属性的结构。我想为此结构实现IntoIterator特征,以便我可以迭代其HashMap属性。问题是我遇到了终身地狱:

pub struct ProcessList {
    map: HashMap<ProcessPtr, usize>,
}

impl ProcessList {
    pub fn new() -> ProcessList {
        ProcessList {
            map: HashMap::new(),
        }
    }

    pub fn add(self, process: ProcessPtr, nb: usize) {
        match self.map.contain_key(process) {
            true => self.map[process] += nb,
            false => self.map.insert(process, nb),
        };
    }
}

impl<'a> IntoIterator for ProcessList {
    type Item = (&'a ProcessPtr, &'a usize);
    type IntoIter = Iter<'a, ProcessPtr, usize>;

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

1 个答案:

答案 0 :(得分:2)

了解stdlib sourceIntoIterator HashMap的实施情况

如果您希望IntoIterator实现ProcessList,则根本不需要引用和生命周期:

use std::collections::HashMap;
use std::collections::hash_map::IntoIter;

#[derive(Eq,PartialEq,Hash)]
pub struct ProcessPtr;

pub struct ProcessList {
    map: HashMap<ProcessPtr, usize>,
}

impl ProcessList {
    pub fn new() -> ProcessList {
        ProcessList {
            map: HashMap::new(),
        }
    }

    pub fn add(self, process: ProcessPtr, nb: usize) {
    /* Bunch of errors here
        match self.map.contains_key(process) {
            true => self.map[process] += nb,
            false => self.map.insert(process, nb),
        };
    */
    }
}

impl IntoIterator for ProcessList {
    type Item = (ProcessPtr, usize);
    type IntoIter = IntoIter<ProcessPtr, usize>;

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

fn main(){
}

此外,您的代码中包含add函数中的一些错误。