[英]Rust: cannot infer an appropriate lifetime for autoref due to conflicting requirements
Minimal reproducible code:最小的可重现代码:
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())
}
}
Getting error message:收到错误信息:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
When using self.a.iter().map(|o| o.as_ref()).collect()
, it compiles.当使用
self.a.iter().map(|o| o.as_ref()).collect()
时,它会编译。
I've already read the explain document, but I still don't know why this error occurs and how to solve it.我已经阅读了说明文档,但我仍然不知道为什么会出现这个错误以及如何解决它。
When the map
call in A.foo
is replaced with the code from the map
function, it compiles, which indicates that the issue is with the trait definition not constraining the lifetime of the argument passed to the closure.当 A.foo 中的
map
调用被map
A.foo
中的代码替换时,它会编译,这表明问题出在传递给闭包的特征定义的参数上。
In the case of fn map(&self, f: impl Fn(&T) -> R) -> Vec<R>
, the lifetime of the reference passed as &T
in impl Fn(&T) -> R
must live for at least as long as the &self
argument passed into it.在
fn map(&self, f: impl Fn(&T) -> R) -> Vec<R>
的情况下,在impl Fn(&T) -> R
中作为&T
传递的引用的生命周期必须至少为只要&self
参数传递给它。 The following changes should make it compile以下更改应使其编译
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.