【发布时间】:2023-03-29 22:25:01
【问题描述】:
我写了下面的代码,但是我不能写生命周期约束来工作并报错:
use futures::Future;
async fn foo<'a>(a: &'a str) -> &'a str {
let task = get();
f(a, task).await
}
async fn f<T>(v: T, task: impl Future<Output = T>) -> T {
if true {
v
} else {
task.await
}
}
async fn get() -> &'static str {
"foo"
}
错误:
error[E0759]: `a` has lifetime `'a` but it needs to satisfy a `'static` lifetime requirement
--> src/lib.rs:3:18
|
3 | async fn foo<'a>(a: &'a str) -> &'a str {
| ^ ------- this data with lifetime `'a`...
| |
| ...is captured here...
4 | let task = get();
5 | f(a, task).await
| - ...and is required to live as long as `'static` here
如果函数f中的两个参数可以有自己的生命周期,我认为可以解决。
例如,
v: T,
task: S,
T: 'a,
S: 'b,
'b: 'a,
S == T
如何解决这个问题?
【问题讨论】:
-
你的意思是:
fn f<'a, 'b: 'a, T>(v: &'a T, task: impl Future<Output = &'b T>) -> &'a T? -
没有。
T是一个包含生命周期参数的结构,例如Cow<'a, str>。所以我不能将T重写为&'a T。 -
您的示例代码可以trivially be fixed by using a second type parameter
Ufor the output type of theFuture。您的示例代码没有说明为什么T和U除了它们的生命周期之外需要是相同的类型。您的问题仅说明问题的尝试解决方案,而不是实际问题本身。很可能该解决方案没有声明两个除生命周期外相同的泛型类型参数,但如果没有更多信息,我们无法判断。 -
谢谢。我修正了我的例子。我面临的真正问题更复杂,我不想在这里粘贴代码,因为我想展示 MVCE。
-
我想知道为什么编译器会抱怨
a的生命周期必须是static,尽管T: 'a是必需且足够的。