如果我删除'static最后一个参数的生命周期,程序就会编译。如果我把它加回去,就会失败。对我来说,似乎两者都应该有效。最小复制:
use std::io;
struct Foo {
user: String,
pass: String,
}
impl Foo {
async fn not_works(
&mut self,
user: &str,
pass: &str,
app_name: &'static str,
) -> io::Result<()> {
self.user = user.to_string() + app_name;
self.pass = pass.to_string();
self.do_stuff().await
}
async fn works(&mut self, user: &str, pass: &str, app_name: &str) -> io::Result<()> {
self.user = user.to_string() + app_name;
self.pass = pass.to_string();
self.do_stuff().await
}
async fn do_stuff(&self) -> io::Result<()> {
Ok(())
}
}
#[tokio::main]
async fn main() {
let mut foo = Foo {
user: "".to_string(),
pass: "".to_string(),
};
foo.not_works("test", "password", "foobar").await.unwrap();
}
Run Code Online (Sandbox Code Playgroud)
error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
--> src/main.rs:14:10
|
14 | ) -> io::Result<()> {
| ^^^^^^^^^^^^^^
|
note: hidden type `impl Future` captures lifetime smaller than the function body
--> src/main.rs:14:10
|
14 | ) -> io::Result<()> {
| ^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
更有可能的是,这个错误是在我的理解中,而不是编译器。我缺少什么?
这是实施的限制async fn。基本上,它试图将所有生命周期统一为相同,在这种情况下,它们不可能全部相同'static。
这有效:
fn workaround<'a>(
&'a mut self,
user: &'a str,
pass: &'a str,
app_name: &'static str,
) -> impl Future<Output = io::Result<()>> + 'a {
async move {
self.user = user.to_string() + app_name;
self.pass = pass.to_string();
self.do_stuff().await
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4639 次 |
| 最近记录: |