我需要告诉编译器 F
返回实现 SomeTrait
的东西,生命周期为 'a
:
trait SomeTrait {}
fn foo<P, Q, F>(func: F)
where
Q: SomeTrait,
F: for<'a> Fn(&'a P) -> Q + 'a,
{}
但是我得到这个错误:
error[E0261]: use of undeclared lifetime name `'a`
--> src/main.rs:6:33
|
6 | F: for<'a> Fn(&'a P) -> Q + 'a,
| ^^ undeclared lifetime
就好像它不理解Q + 'a
。
最佳答案
Q
不是特质,是类型;类似 T: Q + 'a
的东西没有意义。
如果你尝试 F: for<'a> Fn(&'a P) -> (Q + 'a)
你会得到:
error[E0404]: expected trait, found type parameter `Q`
您的示例实际上解析为 F: (for<'a> Fn(&'a P) -> Q) + 'a
- 为什么这不起作用应该很明显。
现在:
I need to tell the compiler that
F
returns something that implementsSomeTrait
with lifetime'a
.
除了将这些生命周期用于引用或通用生命周期参数之外,您的函数不能根据(传递的)生命周期返回不同的类型。您可以编写一个完全忽略生命周期的 Rust 编译器,如果原始程序有效,它仍然会做同样的事情。
目前还没有办法为生命周期或类型指定采用泛型参数的类型参数。
如果有,它可能看起来像这样:
trait SomeTrait {}
fn foo<P, for<'a> Q<'a>, F>(func: F)
where
for<'a> Q<'a>: SomeTrait,
for<'a> F: Fn(&'a P) -> Q<'a>,
{
}
关于rust - 如何指定一个接受引用并返回实现与引用具有相同生命周期的特征的任何类型的闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48355092/