2

我正在从 rust book 设置服务器示例。我将在这里添加相关部分。

trait FnBox {
    fn call_box(self: Box<Self>);
}

impl<F: FnOnce()> FnBox for F {
    fn call_box(self: Box<F>) {
        (*self)()
    }
}
type Job = Box<dyn FnOnce() + Send + 'static>;

我的实现与书中略有不同。它FnBox在书中而不是FnOnce(). 我打电话给

job.call_box()

这里job是类型Job。但这会引发错误。

   |             job.call_box();
   |                 ^^^^^^^^
   |
   = note: job is a function, perhaps you wish to call it
   = note: the method `call_box` exists but the following trait bounds were not satisfied:
           `dyn std::ops::FnOnce() + std::marker::Send : FnBox`
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `call_box`, perhaps you need to implement it:
           candidate #1: `FnBox`

该特征FnBox已在所有具有FnOnce()特征的类型上实现。所以我不明白为什么它说dyn std::ops::FnOnce() + std::marker::Send : FnBox不满意。

我在这里想念什么?

4

1 回答 1

1

我认为问题在于for your trait 中的隐含Sized约束,这使得 a未涵盖在 that 之下。FimplFnBoxBox<dyn T>impl

你说

特征 FnBox 已在具有 FnOnce() 特征的所有类型上实现。

但实际上,特性 FnBox 仅针对具有 FnOnce() 特性的所有Sized类型实现。Sized 的文档对此有更多信息。

一个工作示例是:

trait FnBox {
    fn call_box(self: Box<Self>);
}

impl<F: FnOnce() + ?Sized> FnBox for F {
    fn call_box(self: Box<F>) {
        (self)()
    }
}
type Job = Box<dyn FnOnce() + Send + 'static>;

let job: Job = Box::new(|| println!("gwahhh"));
job.call_box();

请注意,我必须删除(*self)()赞成的,(self)()因为您不能将未调整大小的类型移出Box.

操场

于 2019-08-01T15:15:13.660 回答