gpt4 book ai didi

rust - 如何在 rust 中声明除生命周期之外的相同类型的泛型参数?

转载 作者:行者123 更新时间:2023-12-03 11:24:19 24 4
gpt4 key购买 nike

我写了下面的代码,但我不能写生命时间约束来工作并得到一个错误:

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

playground
我认为如果函数 f中有两个参数可以解决可以有自己的一生。
例如,
v: T,
task: S,
T: 'a,
S: 'b,
'b: 'a,
S == T
如何解决这个问题?

最佳答案

同样的问题可以用另一个最小的例子来重现,使用函数接口(interface)而不是异步函数。

fn get() -> impl FnOnce() -> &'static str {
|| "foo"
}

fn foo<'a, T: 'a, F>(_: &'a str, _: F)
where
F: Fn() -> T,
T: FnOnce() -> &'a str,
{
}

let x = "".to_string();
foo(&*x, &get);
error[E0597]: `x` does not live long enough
--> src/main.rs:22:11
|
22 | foo(&*x, &get);
| ------^-------
| | |
| | borrowed value does not live long enough
| argument requires that `x` is borrowed for `'static`
23 | }
| - `x` dropped here while still borrowed
这个例子可以让我们转 get进入函数参数并观察传递此函数会对生命周期施加硬约束 'a成为 'static .尽管程序有最好的意图,但返回供应商函数(或 promise )的函数不会提供关于输出生命周期的协方差。也就是说, () -> &'static str不满足 for<'a> () -> &'a str .有时,编译器会回退到建议您坚持最薄弱的环节,即 'static。终生,即使这可能是不可取的。
请注意,目前表示在其生命周期内通用的类型的方法非常有限。这些是更高种类的类型的一种形式,只能通过更高等级的特征边界(以及最终的通用关联类型,一旦它们完全实现和稳定)来指定某种程度的表现力。在这种情况下,而不是试图使 f为一种工作 T<'a> (伪代码),最好只制作我们的 get终身通用 'a .然后子类型化可能会在实现中发生,因为我们知道字符串文字可以满足任何生命周期。
fn get<'a>() -> impl FnOnce() -> &'a str {
|| "foo"
}
async案例( Playground):
async fn get<'a>() -> &'a str {
"foo"
}
也可以看看:
  • The compiler suggests I add a 'static lifetime because the parameter type may not live long enough, but I don't think that's what I want
  • How can this instance seemingly outlive its own parameter lifetime?
  • How can we write a generic function for checking Serde serialization and deserialization?
  • 关于rust - 如何在 rust 中声明除生命周期之外的相同类型的泛型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65769775/

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