pub struct FooStruct<'a> {
pub bars: Vec<&'a str>,
}
pub trait FooTrait<'a> {
fn getBars(&self) -> &'a Vec<&'a str>;
}
impl<'a> FooTrait<'a> for FooStruct<'a> {
fn getBars(&self) -> &'a Vec<&'a str> {
&self.bars // cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
}
}
我不知道需求冲突的来源。 Afaik没有冲突,因为只要FooStruct
存在,一切都会存在。
让我们拆开它:
pub struct FooStruct<'a> {
pub bars: Vec<&'a str>,
}
FooStruct
保存一个包含寿命为'a
的字符串切片的容器。容器的寿命对应于FooStruct
的寿命。
pub trait FooTrait<'a> {
fn getBars(&self) -> &'a Vec<&'a str>;
}
FooTrait
希望getBars
返回对包含生存期为'a
的字符串切片的容器的引用。返回的引用的生存期也应为'a
。
impl<'a> FooTrait<'a> for FooStruct<'a> {
fn getBars(&self) -> &'a Vec<&'a str> {
&self.bars
}
}
[此处,getBars
返回对self.bars
的引用,该引用是具有生存期'a
的字符串切片的容器。到现在为止还挺好。
&self.bars
的寿命是多少?它对应于self
的生存期(即相应的FooStruct
)。self
的寿命是多少?它是'self
(隐式生存期)。但是,FooTrait
要求返回的参考生存期为'a
,因此与FooTrait
的声明不匹配。
一种解决方案是将FooTrait
中的生存期分开:
pub trait FooTrait<'a> {
fn getBars<'s>(&'s self) -> &'s Vec<&'a str>;
}
impl<'a> FooTrait<'a> for FooStruct<'a> {
fn getBars<'s>(&'s self) -> &'s Vec<&'a str> {
&self.bars
}
}