I wrote the code below, but I can't write life time constraint to work and get an error:
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:
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
I think it can be solved if two parameters in function f
can have their own lifetimes.
For example,
v: T,
task: S,
T: 'a,
S: 'b,
'b: 'a,
S == T
How to solve this issue?
fn f<'a, 'b: 'a, T>(v: &'a T, task: impl Future<Output = &'b T>) -> &'a T
? – TrawlerT
is a struct containing lifetime parameter likeCow<'a, str>
. So I cannot rewriteT
as&'a T
. – HollishollisterU
for the output type of theFuture
. Your example code doesn't demonstrate whyT
andU
need to be the same types except for their lifetimes. Your question only states an attempted solution for a problem, but not the actual problem itself. Chances are that the solution isn't declaring two generic type parameters that are the same except for the lifetime, but we can't tell without more information. – Mlawskya
's lifetime must bestatic
, althoughT: 'a
is required and sufficient. – Hollishollister'static
becauseget
returns a&'static str
, so the compiler infers thatT == &'static str
. – TrawlerT==&'a str
? – Hollishollister