0

我有一个循环将项目从队列中弹出,使用项目调用回调,然后需要将项目重新添加到队列中。这样做的原因是这些项目实际上是重复计时器,但是为了简洁起见,我在这个简单的示例中删除了所有计时器代码。是否可以在移动项目后克隆项目,或者有更好的方法来处理这个问题?

pub trait ItemCb: Send {
    fn call(&mut self, item: Item);
}

impl<F: Send> ItemCb for F
where
    F: FnMut(Item),
{
    fn call(&mut self, item: Item) {
        self(item)
    }
}

pub struct Item<'a> {
    cb: Option<Box<dyn ItemCb + 'a>>,
    data: i32,
}

impl<'a> Item<'a> {
    pub fn new(cb: impl ItemCb + 'a, data: i32) -> Self {
        Self {
            cb: Some(Box::new(cb)),
            data,
        }
    }
}

fn main() {
    let mut items = vec![Item::new(|_i: Item| println!("hello world!"), 1)];
    loop {
        if let Some(mut item) = items.pop() {
            // TODO cannot clone item
            let cloned_item = item.clone();

            let mut cb = item.cb.take().unwrap();
            cb.call(item);

            // Add the item back to the queue to be processed again
            items.push(cloned_item);
        }
    }
}
error[E0599]: no method named `clone` found for struct `Item<'_>` in the current scope
   --> src/main.rs:33:36
    |
14  | pub struct Item<'a> {
    | ------------------- method `clone` not found for this
...
33  |             let cloned_item = item.clone();
    |                                    ^^^^^ method not found in `Item<'_>`
    |
    = help: items from traits can only be used if the trait is implemented and in scope
    = note: the following trait defines an item `clone`, perhaps you need to implement it:
            candidate #1: `Clone`
4

0 回答 0