嵌套异步函数调用导致生命周期问题

Nested async function call causes lifetime issue

我觉得我完全迷失了;错误消息中的“'1”是什么意思?

error[E0597]: `o` does not live long enough
  --> src/main.rs:32:19
   |
31 |     async fn foo6(&mut self, mut o: &'a mut Outer) {
   |                   --------- lifetime `'1` appears in the type of `self`
32 |         self.foo5(&mut o).await
   |         ----------^^^^^^-
   |         |         |
   |         |         borrowed value does not live long enough
   |         argument requires that `o` is borrowed for `'1`
33 |     }
   |     - `o` dropped here while still borrowed

我该怎么做才能让 o 活得足够长?我想我正在使用期货 03.

use futures::future::BoxFuture;
use futures::FutureExt;
use futures::stream::FuturesOrdered;

struct Inner {}

impl Inner {
    async fn foo3(&mut self) -> Result<u32, ()> {
        Ok(8)
    }
}

// --- 1 
struct Outer {
    i: Inner,
}

impl Outer {
    fn foo4(&mut self) -> BoxFuture<'_, Result<u32, ()>> {
        self.i.foo3().boxed()
    }
}

/// --- 2
struct Outer2<'a> {
    futures_list: FuturesOrdered<BoxFuture<'a, Result<u32, ()>>>,
}


impl <'a> Outer2<'a> {
    async fn foo6(&mut self, mut o: &'a mut Outer) {
        self.foo5(&mut o).await
    }
    
    async fn foo5(&mut self, o: &'a mut Outer) {
        self.futures_list.push(o.foo4());
    }
}

#[tokio::main]
async fn main() {
    let mut o = Outer { i: Inner {} };
    
    let mut o2 = Outer2 { futures_list: FuturesOrdered::new() };
    o2.foo5(&mut o).await;
}

playground

'1 表示函数 foo5self 参数的匿名生命周期。

请注意,在 foo6 中,o 已经是对 Outer 的可变引用,因此编写 &mut o 实际上为您提供了对 [= 的可变引用的可变引用=16=] 有太多的间接寻址。您可以通过删除额外的参考来修复您的代码:

async fn foo6(&mut self, mut o: &'a mut Outer) {
    self.foo5(o).await
}

Playground