我有一个类型为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()
}
}
答案 0 :(得分:2)
了解stdlib source中IntoIterator
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
函数中的一些错误。