我正在使用specs crate,它具有Component
扩展std::any::Any
特性的特性(Any
特性只需要'static
)。我想在实现的结构中包含一个Box<Fn(T) + 'static>
字段(带有通用参数T
)Component
,这意味着Box<Fn(T) + 'static>
需要是'static
. 这意味着我需要Fn(T) + 'static
为'static
任何T
。
它似乎Fn(T) + 'static
不适'static
用于任何泛型类型参数T
。T
可以引用具有自己生命周期的结构,但我预计它不会成为问题,因为在 中没有具有这些生命周期的引用实例Fn
来使Fn
自身不存在'static
- 这些生命周期仅在传递给 的参数中Fn
,但是就好像Fn(T) + 'static
被认为包含一个T
本身。
例子:
struct HandlesT<T> {
handler: Box<Fn(T) + 'static>,
}
impl<T> HandlesT<T> {
pub fn new<F: Fn(T) + 'static>(handler: F) -> HandlesT<T> {
HandlesT {
handler: Box::new(handler),
}
}
}
trait IsStatic: 'static {}
impl<T> IsStatic for HandlesT<T> {}
error[E0310]: the parameter type `T` may not live long enough
--> src/lib.rs:14:9
|
14 | impl<T> IsStatic for HandlesT<T> {}
| - ^^^^^^^^
| |
| help: consider adding an explicit lifetime bound `T: 'static`...
|
note: ...so that the type `HandlesT<T>` will meet its required lifetime bounds
--> src/lib.rs:14:9
|
14 | impl<T> IsStatic for HandlesT<T> {}
| ^^^^^^^^
在这个例子中,因为HandlesT<T>
对于任何给定的引用根本不包含非静态引用T
(除了那些由 拥有的引用之外根本没有引用Fn
,但那些必须是'static
),我希望HandlesT<T>
对于 any 是静态的T
,但错误表明它不是。
编译器的建议“考虑加入势必明确的一生T: 'static
”既不支持任何泛型类型参数T,也没有提供线索,为什么HandlesT<T>
任何通用的T
不是'static
,因为HandlesT<T>
不包含T
。
的实施例T: 'static
(编译器的建议)不支持任何通用T
,在这种情况下&'a i32
:
struct HandlesT<T: 'static> {
handler: Box<Fn(T) + 'static>,
}
impl<T: 'static> HandlesT<T> {
pub fn new<F: Fn(T) + 'static>(handler: F) -> HandlesT<T> {
HandlesT {
handler: Box::new(handler),
}
}
}
trait IsStatic: 'static {}
impl<T: 'static> IsStatic for HandlesT<T> {}
fn try_nonstatic_t<'a>() {
let handles_t = HandlesT {
handler: Box::new(|i: &'a i32| {}),
};
}
error[E0477]: the type `&'a i32` does not fulfill the required lifetime
--> src\lib.rs:17:21
|
17 | let handles_t = HandlesT {
| ^^^^^^^^
|
= note: type must satisfy the static lifetime
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句