我正在尝试将函数存储在结构中:
trait T<'a> {}
struct A {}
struct B<'a> {
a: &'a A
}
impl<'a> T<'a> for B<'a> {}
fn f1<'a, E: T<'a>>(a: &'a A) {}
struct D {
f: fn(&A)
}
fn main() {
let d = D { f: f1::<B> };
}
编译器提示:
error[E0308]: mismatched types
--> src/main.rs:18:20
|
18 | let d = D { f: f1::<B> };
| ^^^^^^^ expected concrete lifetime, found bound lifetime parameter
|
= note: expected type `fn(&A)`
= note: found type `fn(&A) {f1::<'_, B<'_>>}`
最佳答案
当你写 f1::<B>
,编译器将其解释为 f1::<B<'_>>
, 那里 '_
是编译器推断的生命周期,因为 B
在整个生命周期内都是通用的,您只能将具体类型作为类型参数传递。
但是,在 D
, f
字段应该是一个函数,它接受对 A
的引用任何一生。 f1::<B>
不满足该要求,因为该函数已实例化并具有特定的生命周期。
不幸的是,目前还没有办法让这项工作成功。 Rust 必须支持 higher kinded types或 associated type constructors .然后你可以定义 E
在f1
成为类型构造函数参数,而不是类型参数(尽管我想知道编译器将如何处理 'a
生命周期参数)。
关于rust - 预期的具体生命周期,在结构中存储 fn 时找到绑定(bind)生命周期参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41087239/