[英]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.