[英]Expected concrete lifetime, found bound lifetime parameter when storing a fn in a struct
I'm trying to store a function in a struct: 我正在尝试将函数存储在结构中:
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> };
}
The compiler complains: 编译器抱怨:
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<'_>>}`
When you write f1::<B>
, the compiler interprets that as f1::<B<'_>>
, there '_
is a lifetime inferred by the compiler, because B
is generic over a lifetime and you can only pass concrete types as type parameters. 当您编写
f1::<B>
,编译器将其解释为f1::<B<'_>>
,编译器会推断出'_
的生存期,因为B
在整个生存期内都是通用的,您只能传递具体的类型作为类型参数。
But then, in D
, the f
field is expected to be a function that accepts references to A
with any lifetime. 但是,在
D
, f
字段应该是一个可以接受任何生存期的对A
引用的函数。 f1::<B>
does not fulfill that requirement, because the function has been instantiated with a specific lifetime. f1::<B>
不满足该要求,因为该函数已使用特定的生存期进行了实例化。
Unfortunately, at the moment, there's no way to make this work. 不幸的是,目前还没有办法使它起作用。 Rust would have to support either higher kinded types or associated type constructors .
Rust将必须支持更高种类的类型或关联的类型构造函数 。 You could then define
E
in f1
to be a type constructor parameter, rather than a type parameter (though I'm wondering how the compiler would handle the 'a
lifetime parameter). 然后,您可以在
f1
中将E
定义为类型构造函数参数,而不是类型参数(尽管我想知道编译器将如何处理'a
lifetime参数'a
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.