gpt4 book ai didi

rust - 异步 fn 报告 "hidden type for ` impl Trait` 捕获未出现在边界中的生命周期”

转载 作者:行者123 更新时间:2023-12-04 14:53:39 25 4
gpt4 key购买 nike

如果我删除 'static最后一个参数的生命周期,程序编译。如果我把它加回来,它就会失败。对我来说,似乎两者都应该有效。 Minimal reproduction :

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();
}
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<()> {
| ^^^^^^^^^^^^^^
不过,这个错误更有可能在我的理解中,而不是编译器。我错过了什么?

最佳答案

这是a limitation of the async fn implementation .基本上,它试图将所有生命周期统一为相同,在这种情况下,它们不能都是 '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
}
}

关于rust - 异步 fn 报告 "hidden type for ` impl Trait` 捕获未出现在边界中的生命周期”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68591843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com