我试图实现一个可以无限迭代的 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(¶m);
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
相同,而预期的行为是,前一个g
的hash
将等于SHA256(game.hash),下一个g
的hash将是SHA256(SHA256(game.hash)).当我拨打.next()
时,它工作正常.