我正在尝试实现一个可以无限迭代的结构。把它想象成一个自然数。我有一个限制:它无法实现Copy
特征,因为该结构包含String
field.
我还实现了一个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()
.