< 返回版块

林深好材 发表于 2024-07-29 10:50

Tags:Iterator

对象应如下:

  pub struct Target {
    exchange: String,
    instrument: String,
  }

  pub struct Targets(HashSet<Target>);

现想实现Iterator


  impl Iterator for Targets{
     type Item = Target;

     fn next(&mut self) -> Option<Self::Item> {
        todo!("怎么实现呢")
     }
  }

既然是求next,那么肯定有current,这个current信息存放在哪?

评论区

写评论
Bai-Jinlin 2024-07-30 09:26
impl IntoIterator for Targets {
    type Item = Target;

    type IntoIter = std::collections::hash_set::IntoIter<Self::Item>;

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

let ts = Targets(HashSet::new());
for t in ts {
    //xxx
}

作者 林深好材 2024-07-30 08:49

尽管很妙,但是有些魔法

--
👇
facefaceless: 可以解引用为内部的HashSet

impl Deref for Targets {
    type Target = std::collections::HashSet<Target>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[test]
fn test() {
    let targets = Targets(std::collections::HashSet::new());
    for target in targets.iter() {
        todo!()
    }
}
facefaceless 2024-07-29 15:27

可以解引用为内部的HashSet

impl Deref for Targets {
    type Target = std::collections::HashSet<Target>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[test]
fn test() {
    let targets = Targets(std::collections::HashSet::new());
    for target in targets.iter() {
        todo!()
    }
}
gwy15 2024-07-29 10:56
impl IntoIterator for Targets {

}
struct TargetsIter {
    inner: hashset::Iter<>
}
impl Iterator for TargetsIter {
}

多看 std 代码怎么做的

1 共 4 条评论, 1 页