由于需求冲突,无法推断出借位表达的适当期限

问题描述 投票:0回答:1
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存在,一切都会存在。

reference rust lifetime
1个回答
0
投票

让我们拆开它:

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
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.