我正在实现一个 struct ,该 struct 包含对状态集合的引用,并能够以循环方式遍历该引用.
struct Pawn {
_state: Box<dyn Iterator<Item = u8>>,
}
impl Pawn {
const ALL_STATES: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
fn new() -> Self {
Pawn { _state: Box::new(Self::ALL_STATES.into_iter().cycle()) }
}
fn tick(&mut self, steps: usize) -> u8 {
(0..steps - 1).for_each(|_| {self._state.next();});
self._state.next().unwrap()
}
}
impl Clone for Pawn {
fn clone(&self) -> Self {
Self { _state: Box::new(*self._state.as_ref().clone()) }
}
}
构造函数和tick
方法按其应有的方式工作.但我也想为这个 struct 实现Clone
.这就是我迷路的地方:
the size for values of type `dyn Iterator<Item = u8>` cannot be known at compilation time
the trait `Sized` is not implemented for `dyn Iterator<Item = u8>`
由于动态分派,我似乎不能从编译时未知的东西中生成一个新的Box
.我知道这将始终是指向u8
的迭代器,但我不知道如何告诉编译器.