【发布时间】:2021-02-21 18:45:45
【问题描述】:
今天我在玩功能特征。虽然我在下面展示的示例实际上可能不是很有用,但我确实想知道为什么它不能编译。
pub fn do_something(o: &(dyn Other + 'static)) {
}
trait Other {
fn do_something_other(&self);
}
impl<A> Other for dyn Fn(A) {
fn do_something_other(&self) {
do_something(self);
}
}
这里我实现了一个函数类型的特征。此函数类型对其参数是通用的。这意味着如果您要这样做:
pub fn do_something(o: &(dyn Other + 'static)) {
}
trait Other {
fn do_something_other(&self);
}
impl<F, A> Other for F where F: (Fn(A)) + 'static {
fn do_something_other(&self) {
do_something(self);
}
}
我明白这一点,但不相信使用泛型可以做到这一点。但是动态方法,为什么不起作用?它给出了以下错误:
我不明白这个错误。它声明我通过了一个Fn(A) -> (),它没有实现Other。然而,这个错误确实发生在Other 的实现中。这里怎么不能实现?
我的第一个想法是因为每个闭包都有自己的类型。如果和这个有关,我觉得这个错误很奇怪。
【问题讨论】:
-
为什么要在 dyn Fn 上实现 trait 而你可以在 Fn 上实现呢?
impl<F> MyTrait for F where F: Fn(...) -
这正是我在问题的第二个示例中所解释的。你不能,因为这会给出“不受约束的生命周期参数”错误
标签: rust function-pointers traits