无法推断异步方法的生命周期

时间:2020-10-17 09:20:34

标签: rust async-await reference lifetime

考虑以下代码:

struct Base{
    value: u32
}

impl Base{
    async fn create_test_async(&self, some_string: &str) -> Option<Test>{ //error
        None
    }
    
    fn create_test(&self, some_string: &str) -> Option<Test>{ //ok
        None
    }
}

struct Test<'a>{
    value: &'a u32
}

Playground

async fn create_test_async无法编译并显示以下错误:

error[E0726]: implicit elided lifetime not allowed here
 --> src/lib.rs:6:68
  |
6 |     async fn create_test_async(&self, some_string: &str) -> Option<Test>{
  |                                                                    ^^^^- help: indicate the anonymous lifetime: `<'_>`

当然可以通过将生命周期参数指定为

来解决
async fn create_test_async<'a>(&'a self, some_string: &str) -> Option<Test<'a>>{
    None
}

问题::为什么需要为async方法显式指定生存期参数?是什么阻止了铁锈的推断?

0 个答案:

没有答案