[英]Why Rust complains about lifetime of types in functions that don't use instances of these types?
Rust requires lifetimes for types that don't have instances: Rust 需要没有实例的类型的生命周期:
use futures::future::BoxFuture;
struct A{
}
impl A{
async fn send_and_expect<T>(&mut self, unauthorized_retry: i32) -> std::result::Result<(),()>{
Err(())
}
fn send_and_expect_wrapper<'a, T>(&'a mut self, unauthorized_retry: i32)
-> BoxFuture<'a, std::result::Result<(),()>> {
Box::pin(self.send_and_expect::<T>(unauthorized_retry))
}
}
Error:错误:
Standard Error
Compiling playground v0.0.1 (/playground)
error[E0309]: the parameter type `T` may not live long enough
--> src/lib.rs:15:9
|
13 | fn send_and_expect_wrapper<'a, T>(&'a mut self, unauthorized_retry: i32)
| - help: consider adding an explicit lifetime bound...: `T: 'a`
14 | -> BoxFuture<'a, std::result::Result<(),()>> {
15 | Box::pin(self.send_and_expect::<T>(unauthorized_retry))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...so that the type `impl futures::Future` will meet its required lifetime bounds
error: aborting due to previous error
For more information about this error, try `rustc --explain E0309`.
error: could not compile `playground`
To learn more, run the command again with --verbose.
I have to do fn send_and_expect_wrapper<'a, T>(&'a mut self, unauthorized_retry: i32)
我必须做fn send_and_expect_wrapper<'a, T>(&'a mut self, unauthorized_retry: i32)
Is there a reason?有原因吗? I never use an instance of T
so there are no concerns about lifetime.我从不使用T
的实例,所以不用担心生命周期。
The type check does checking on types .类型检查确实检查 types 。 From its point of view, a value only does propagating it's type and triggering actions on the type (such as coercing).从它的角度来看,一个值只会传播它的类型并触发对该类型的操作(例如强制)。 And in your example T
is involved into unsized coercion with : 'a
bound.在您的示例中, T
涉及到无大小的强制转换: 'a
bound。 Why?为什么? See how BoxFuture
is declared 看看BoxFuture
是如何声明的
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a, Global>>;
Desugared and extremely minimized example would be like:脱糖和极小化的示例如下:
pub trait Future {}
struct Closure<'a, T> {
receiver: &'a mut (),
params: std::marker::PhantomData<T>,
}
impl<'a, T> Future for Closure<'a, T> {}
fn foo<'a, T>() {
let x: *mut Closure<'a, T>;
let coerced: *mut (dyn Future + 'a) = x;
}
This gives the same error[E0309]
.这给出了相同的error[E0309]
。
The point is in a type checking rule: U = dyn _ + 'a
implies U: 'a
.关键在于类型检查规则: U = dyn _ + 'a
暗示U: 'a
。 Or simply (dyn _ + 'a): 'a
或者简单地说(dyn _ + 'a): 'a
Applying this to our example ( U = Closure<'a, T>
) we get Closure<'a, T>: 'a
which implies the same bound should hold on the substitutions, ie 'a: 'a
and T: 'a
.将此应用于我们的示例( U = Closure<'a, T>
)我们得到Closure<'a, T>: 'a
这意味着相同的界限应该适用于替换,即'a: 'a
和T: 'a
. But our environment (the foo
fn signature) tells nothing about the T: 'a
requirement, hence the error.但是我们的环境( foo
fn 签名)没有说明T: 'a
要求,因此错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.