为什么此FnMut需要明确的生命周期

问题描述

以下示例确实进行了编译(Playground):

use std::future::Future;

static API: Api = Api;

#[derive(Debug)]
struct Api;

async fn with_api<'a,F,Fut>(f: F) -> Fut::Output
where
    F: FnOnce(&'a Api) -> Fut,Fut: Future<Output = ()>,{
    f(&API).await
}

fn main() {
    with_api(|api| async move {
        println!("{:?}",api);
    });
}

但是,在删除显式生存期'a时,出现此错误

error: lifetime may not live long enough
  --> src/main.rs:17:20
   |
17 |       with_api(|api| async move {
   |  _______________----_^
   | |               |  |
   | |               |  return type of closure is impl std::future::Future
   | |               has type `&'1 Api`
18 | |         println!("{:?}",api);
19 | |     });
   | |_____^ returning this value requires that `'1` must outlive `'2`

对此我有两个问题:

  1. 这是什么问题?具体来说,生命周期'2是什么?

  2. 为什么要添加显式生存期来固定编译,它与推断的生存期有何不同?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)