簡體   English   中英

Rust 使用異步/等待的生命周期

[英]Rust lifetimes with async/await

以下代碼在 function 上無需 async 關鍵字即可工作。將其更改為 async 后,我應該怎么做才能使其工作。

use cgmath::Vector2;
use winit::window::Window;

struct A<'a> {
    a: Option<&'a Vector2<f32>>,
}

impl A<'_> {
    async fn new(b: &Window) -> A<'_> {
        Self {
            a: None
        }
    }
}

編譯錯誤

error: lifetime may not live long enough
 --> src/lib.rs:7:9
9  |       async fn new(b: &Window) -> A<'_> {
   |                       -           ----- return type `impl std::future::Future<Output = lang::A<'_>>` contains a lifetime `'1`
   |                       |
   |                       let's call the lifetime of this reference `'2`
10 | /         Self {
11 | |             a: None
12 | |         }
   | |_________^ associated function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`

我試圖將其更改為

struct A<'a> {
    a: Option<&'a Vector2<f32>>,
}

impl<'a> A<'a> {
    async fn new(b: &'a Window) -> A<'a> {
        Self {
            a: None
        }
    }
}

但是它借用window的時間太長,調用后無法移動window。 在我向結構 A 添加生命周期參數 'a 之前,它起作用了。

46 |       let mut a = A::new(&window).await;
   |                          ------- borrow of `window` occurs here
47 |       //player.init();
48 |       event_loop.run(move |event, _, control_flow| {
   |       -              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ move out of `window` occurs here
   |  _____|
   | |
49 | |         match event {
50 | |             Event::WindowEvent {
51 | |                 ref event,
52 | |                 window_id,
53 | |             } if window_id == window.id() => if !player.input(event) { // UPDATED!
   | |                               ------ move occurs due to use in closure
...  |
92 | |         }
93 | |     });
   | |______- argument requires that `window` is borrowed for `'static`

當您說Self時,您會說“ impl標頭中的A ”。 它包含一生。 我們稱它為'b

impl<'b> A<'b> {
    async fn new<'a>(b: &'a Window) -> A<'a> {
        A::<'b> {
            a: None
        }
    }
}

看到不匹配了嗎? 你應該返回A<'a> ,但你返回A<'b>

解決方法很簡單:也可以使用Self作為返回類型,或者只使用A作為返回表達式:

impl A<'_> {
    async fn new(b: &Window) -> A<'_> {
        A {
            a: None
        }
    }
}

這是通往 go 的方法,b: &Window 不需要與 Aa 相同的生命周期

struct A<'a> {
    a: Option<&'a Vector2<f32>>,
}

impl<'a> A<'a> {
    async fn new(b: &Window) -> A<'a> {
        Self {
            a: None
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM