由于需求冲突,无法为借用表达式推断合适的生命周期

cannot infer an appropriate lifetime for borrow expression due to conflicting requirements

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
  }
}

运行它:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3211c32dd5b9244ff91777f1820ffed5

不明白需求冲突从何而来。 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 到 return 对容器的引用,该容器包含生命周期为 'a 的字符串切片。 returned 引用的生命周期也应该是 'a

impl<'a> FooTrait<'a> for FooStruct<'a> {
  fn getBars(&self) -> &'a Vec<&'a str> {
    &self.bars
  }
}

这里,getBars return 是对 self.bars 的引用,它是生命周期为 'a 的字符串切片的容器。到目前为止,一切都很好。

  • 但是,&self.bars的生命周期是多少?它对应于 self 的生命周期(即相应的 FooStruct)。
  • self 的生命周期是多少?它是 'self(隐式生命周期)。

但是,FooTrait 要求 returned 引用生命周期为 '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
  }
}