[英]Cannot infer an appropriate lifetime for autoref due to conflicting requirements
[英]Rust: cannot infer an appropriate lifetime for autoref due to conflicting requirements
最小的可重现代码:
trait VecExt<T, R> {
fn map(&self, f: impl Fn(&T) -> R) -> Vec<R>;
}
impl<T, R> VecExt<T, R> for Vec<T> {
fn map(&self, f: impl Fn(&T) -> R) -> Vec<R> {
self.iter().map(f).collect()
}
}
struct A {
a: Vec<Option<String>>
}
impl A {
fn foo(&self) -> Vec<Option<&String>> {
self.a.map(|o| o.as_ref())
}
}
收到错误信息:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
当使用self.a.iter().map(|o| o.as_ref()).collect()
时,它会编译。
我已经阅读了说明文档,但我仍然不知道为什么会出现这个错误以及如何解决它。
当 A.foo 中的map
调用被map
A.foo
中的代码替换时,它会编译,这表明问题出在传递给闭包的特征定义的参数上。
在fn map(&self, f: impl Fn(&T) -> R) -> Vec<R>
的情况下,在impl Fn(&T) -> R
中作为&T
传递的引用的生命周期必须至少为只要&self
参数传递给它。 以下更改应使其编译
trait VecExt<'a, T, R> where T: 'a {
fn map(&'a self, f: impl Fn(&'a T) -> R) -> Vec<R>;
}
impl<'a, T, R> VecExt<'a, T, R> for Vec<T> where T: 'a {
fn map(&'a self, f: impl Fn(&'a T) -> R) -> Vec<R> {
self.iter().map(f).collect()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.