我试图实现一个可以无限迭代的 struct .把它当成一个自然数.我有一个限制:它无法实现Copy trait,因为该 struct 包含String字段.

我还实现了一个Iterable trait和它唯一的成员fn next(&mut self) -> Option<Self::Item>.

目前,我有以下代码来迭代我的 struct 的前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; }
}

我想让my crate的用户能够使用for in构造来迭代我的 struct ,如下所示:

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

有可能吗?我怎样才能做到这一点?如何使我的代码更好,以及如何处理我的 struct ?

迭代器实现:

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 struct ,其hash相同,而预期的行为是,前一个ghash将等于SHA256(game.hash),下一个g的hash将是SHA256(SHA256(game.hash)).当我拨打.next()时,它工作正常.

推荐答案

在Rust中,迭代器实际上可以分为两类.因此,拥有 struct 的迭代器可以使用.into_iter()创建,.into_iter()消耗self.

以及迭代 struct 而不使用它的迭代器.它们通常可以使用:.iter.iter_mut()创建

有关更多信息,请参见相关问题:What is the difference between iter and into_iter?

要创建迭代器,您应该实现IntoIterator trait,这将把您的 struct 转换成迭代器,或者编写函数来创建迭代器:iter_mutiter

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

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

按照惯例,你需要两种新的IterMut型和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> {
        /* ... */
    }
}

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

Rust相关问答推荐

Rust kill std::processs::child

将JSON密钥转换为Polars DataFrame

如何容器化Linux上基于Rust的Windows应用程序的编译过程?

rust 蚀生命周期 行为

MPSC频道在接收器处阻塞

在Rust中,在实现特征`Display`时,如何获取调用方指定的格式?

如何将像烫手山芋一样不透明的值从一个Enum构造函数移动到下一个构造函数?

将PathBuf转换为字符串

有没有一种惯用的方法来判断VEC中是否存在变体?

S在Cargo.toml中添加工作空间开发依赖关系的正确方法是什么?

零拷贝按步骤引用一段字节

如何修复&q;无法返回引用函数参数的值在异步规则中返回引用当前函数&q;拥有的数据的值?

对reqwest提供的这种嵌套JSON struct 进行反序列化

要求类型参数有特定的大小?

在使用粗粒度锁访问的数据 struct 中使用 RefCell 是否安全?

注释闭包参数强调使用高阶排定特征界限

如何从trait方法返回std :: iter :: Map?

当 T 不是副本时,为什么取消引用 Box 不会抱怨移出共享引用?

如何解析 Rust 中的 yaml 条件字段?

为实现特征的所有类型实现显示