如何在 Rust 中正确实现 Iterable 结构? [复制]

2024-02-06

我正在尝试实现一个可以无限迭代的结构。把它想象成一个自然数。我有一个限制:它无法实现Copy特征,因为该结构包含String field.

我还实现了一个Iterable特质及其唯一成员fn next(&mut self) -> Option<Self::Item>.

目前,我有以下代码来迭代结构的前 10 项:

let mut counter = 0;
let mut game:Option<Game> = Game::new(&param);
loop {
    println!("{:?}", game); 

    game = g.next();
    counter = counter + 1;
    if counter > 10 { break; }
}

我想给我的用户crate使用迭代我的结构的能力for in施工,像这样:

for next_game in game {
  println!("{:?}", next_game);
} 

有可能吗?我怎样才能实现这个目标?如何使我的代码更好以及我必须如何处理我的结构?

迭代器实现:

pub struct Game {
    /// The game hash
    pub hash: Vec<u8>
}

impl Iterator for Game {
    type Item = Game;

    fn next(&mut self) -> Option<Self::Item> {
        let mut hasher = Sha256::new();
        hasher.input(&hex::encode(&self.hash)); // we need to convert the hash into string first
        let result = hasher.result().to_vec();

        Some(Game {
            hash: result
        })
    }
}

示例:破坏行为for

let mut game:Game = Game::new(&s).unwrap();
for g in game.take(2) {
    println!("{}", g);
}

现在如果我们运行示例,我们将得到两个Game具有相同结构hash,而预期的行为是第一个g将会有hash等于 SHA256(game.hash) 和下一个g的哈希值将为 SHA256(SHA256(game.hash))。当我打电话时它工作正常.next().


在 Rust 中,迭代器实际上可以分为 2 类。拥有该结构的迭代器,因此可以使用以下命令创建.into_iter()哪个消耗self.

以及迭代结构而不消耗它的迭代器。它们通常可以使用以下方式创建:.iter, .iter_mut()

有关更多信息,请参阅相关问题:iter 和 into_iter 有什么区别? https://stackoverflow.com/questions/34733811/what-is-the-difference-between-iter-and-into-iter和文档:迭代的三种形式 https://doc.rust-lang.org/stable/std/iter/#the-three-forms-of-iteration

要创建迭代器,您应该实现IntoIterator特征,它将您的结构转换为迭代器或编写创建迭代器的函数:iter_mut, iter

pub fn iter_mut(&mut self) -> IterMut<T>

pub fn iter(&self) -> Iter<T>

所以按照惯例你需要两种新类型IterMut and Iter

impl Iterator for Iter {
    type Item = /* ... */;
    fn next(&mut self) -> Option<Self::Item> {
        /* ... */
    }
}

impl Iterator for IterMut {
    type Item = &mut /* ... */;
    fn next(&mut self) -> Option<Self::Item> {
        /* ... */
    }
}

它们通常包含对父结构的引用。例如,对于链表,它可以是当前节点(每次迭代都会更新)。对于类似数组的结构,它可以是索引和对父级的引用,因此每次使用索引运算符等访问元素时索引都会递增。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Rust 中正确实现 Iterable 结构? [复制] 的相关文章

随机推荐