<分区>
我正在尝试实现一个可以无限迭代的结构。把它想象成一个自然数。我有一个限制:它无法实现 Copy
特征,因为该结构包含一个 String
字段。
我还实现了 Iterable
特征及其唯一成员fn next(&mut self) -> Option<Self::Item>
.
目前,我有以下代码来迭代结构的前 10 项:
let mut counter = 0;
let mut game:Option<Game> = Game::new(¶m);
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()
时它工作正常.