我正在实现一个 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的迭代器,但我不知道如何告诉编译器.

推荐答案

因为您知道_state的实际类型,并且它是有大小的,所以您可以go 掉所有的特征对象,只需直接定义它.


struct Pawn {
    _state: std::iter::Cycle<std::array::IntoIter<u8, 10>>
}

impl Pawn {
    fn new() -> Self {
        // as before, but remove Box::new
    }
}

impl Clone for Pawn {

    fn clone(&self) -> Self {
        Self { _state: self._state.clone() }
    }
}

注:如果你不知道_state的确切类型,只知道它是一个产生u8的迭代器,如果你在Pawn中将它的类型参数化,你仍然可以定义克隆.请考虑:

struct Pawn<S>
where
    S: Iterator<Item = u8>,
{
    _state: S,
}

impl Pawn<std::iter::Cycle<std::array::IntoIter<u8, 10>>> {
    const ALL_STATES: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    fn new() -> Self {
        Pawn {
            _state: 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()
    }
}

// Note the extra trait bound here! S must also be clone
impl<S> Clone for Pawn<S>
where
    S: Iterator<Item = u8> + Clone,
{
    fn clone(&self) -> Self {
        Self {
            _state: self._state.clone(),
        }
    }
}

Rust相关问答推荐

为什么我们不能通过指针算法将Rust原始指针指向任意地址?'

我怎样才能从一个Rust 的日期中go 掉3年?

在没有引用计数或互斥锁的情况下,可以从Rust回调函数内的封闭作用域访问变量吗?

Arrow RecordBatch as Polars DataFrame

当T不执行Copy时,如何返回Arc Mutex T后面的值?

无法从流中读取Redis请求

在rust sqlx中使用ilike和push bind

为什么`str`类型可以是任意大小(未知大小),而`string`类型的大小应该是已知的?

不同类型泛型的映射

Rust面向对象设计模式

实现 Deref 的 struct 可以返回对外部数据的引用吗?

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

Rust中的一生语法有什么作用?

返回优化后的标题:返回异步块的闭包的类型擦除

使用在功能标志后面导入的类型,即使未启用功能标志

为什么 for_each 在释放模式(cargo run -r)下比 for 循环快得多?

使用 traits 时,borrow 的值不会存在足够长的时间

匹配结果时的简洁日志(log)记录

Rust - 在线程之间不安全地共享没有互斥量的可变数据

tokio async rust 的 yield 是什么意思?