[英]How do I bound a generic type with a trait that requires a lifetime parameter if I create the reference inside the function?
[英]How do I specify a closure that takes a reference and returns any type implementing a trait with the same lifetime as the reference?
我需要告诉编译器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
一样解析F: (for<'a> Fn(&'a P) -> Q) + 'a
- 并且很明显为什么这不起作用。
现在:
我需要告诉编译器
F
返回实现具有生命周期'a
SomeTrait
东西。
除了将这些生命周期用于引用或通用生命周期参数之外,您的函数不能返回不同类型,具体取决于(传递)生命周期。 您可以编写一个完全忽略生命周期的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>,
{
}
生命期只能用于参考 。 将行更改为此作品:
F: for<'a> Fn(&'a P) -> &'a Q
一个对象本身没有“生命周期” - 它一直存在直到被丢弃。 但是,借用检查器必须被告知参考对象相对于其他引用对象指向生命的时间长度。 这就是生命进入的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.