代码之家  ›  专栏  ›  技术社区  ›  user855

嵌套异步函数调用会导致Rust中的生存期问题

  •  0
  • user855  · 技术社区  · 4 年前

    我觉得我完全迷路了,错误信息中的“'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

    0 回复  |  直到 4 年前
        1
  •  0
  •   Jmb    4 年前

    这个 '1 表示的匿名生存期 self 函数的参数 foo5

    请注意 foo6 , o 已经是对的可变引用 Outer ,所以写作 &mut o 外部 有太多的间接指示。您可以通过删除额外的引用来修复代码:

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

    Playground