繁体   English   中英

为什么 Rust 抱怨不使用这些类型实例的函数中类型的生命周期?

[英]Why Rust complains about lifetime of types in functions that don't use instances of these types?

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))
    }
}

错误:

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.

我必须做fn send_and_expect_wrapper<'a, T>(&'a mut self, unauthorized_retry: i32)

有原因吗? 我从不使用T的实例,所以不用担心生命周期。

类型检查确实检查 types 从它的角度来看,一个值只会传播它的类型并触发对该类型的操作(例如强制)。 在您的示例中, T涉及到无大小的强制转换: 'a bound。 为什么? 看看BoxFuture是如何声明的

pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a, Global>>;

脱糖和极小化的示例如下:

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;
}

这给出了相同的error[E0309]

关键在于类型检查规则: U = dyn _ + 'a暗示U: 'a 或者简单地说(dyn _ + 'a): 'a

将此应用于我们的示例( U = Closure<'a, T> )我们得到Closure<'a, T>: 'a这意味着相同的界限应该适用于替换,即'a: 'aT: 'a . 但是我们的环境( foo fn 签名)没有说明T: 'a要求,因此错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM