“不一定比一生都长”问题

use*_*716 0 lifetime rust

我的目标是拥有一个Store包含各种Entry物品的物品。这些Entry物品的寿命比商店本身长,因此Store保留了一个Vec<&Entry>操场):

struct Entry {
    title: String,
    content: String,
}

struct Store<'a> {
    // name: String,
    entries: Vec<&'a Entry>,
}

impl<'a> Store<'a> {
    fn new() -> Store<'a> {
        Store {
            // name,
            entries: Vec::new(),
        }
    }

    fn add_entry(self: &mut Store, entry: &Entry) {
        self.entries.push(entry);
    }
}

fn main() {
    let entry = Entry {
        title: "my title",
        content: "my content",
    };
    let mut store = Store::new();
    store.add_entry(entry);
}
Run Code Online (Sandbox Code Playgroud)
error[E0308]: mismatched `self` parameter type
  --> src/main.rs:19:24
   |
19 |     fn add_entry(self: &mut Store, entry: &Entry) {
   |                        ^^^^^^^^^^ lifetime mismatch
   |
   = note: expected struct `Store<'a>`
              found struct `Store<'_>`
note: the anonymous lifetime #2 defined on the method body at 19:5...
  --> src/main.rs:19:5
   |
19 |     fn add_entry(self: &mut Store, entry: &Entry) {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...does not necessarily outlive the lifetime `'a` as defined on the impl at 11:6
  --> src/main.rs:11:6
   |
11 | impl<'a> Store<'a> {
   |      ^^

error[E0308]: mismatched `self` parameter type
  --> src/main.rs:19:24
   |
19 |     fn add_entry(self: &mut Store, entry: &Entry) {
   |                        ^^^^^^^^^^ lifetime mismatch
   |
   = note: expected struct `Store<'a>`
              found struct `Store<'_>`
note: the lifetime `'a` as defined on the impl at 11:6...
  --> src/main.rs:11:6
   |
11 | impl<'a> Store<'a> {
   |      ^^
note: ...does not necessarily outlive the anonymous lifetime #2 defined on the method body at 19:5
  --> src/main.rs:19:5
   |
19 |     fn add_entry(self: &mut Store, entry: &Entry) {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

在这种情况下,错误 E0308不是很有帮助。

我不明白为什么add_entry方法的生命周期必须比的生命周期长impl,这就是我从错误中理解的。

我确信这是一些非常基本的东西,但我无法通过阅读Rust 编程语言直到第 15 章来弄清楚。

phi*_*mue 5

修复错误以使其编译:add_entry应该如下所示:

fn add_entry(&mut self, entry: &'a Entry) {
    self.entries.push(entry);
}
Run Code Online (Sandbox Code Playgroud)

即您必须明确指定的生命周期entry。您Store假设它的Entrys 有一定的生命周期。如果add_entry没有明确存储此生命周期,Rust 会尝试推断自动生命周期 - 并且它无法证明entry的生命周期实际上是您Store需要的生命周期。

如果您照add_entry原样离开,您基本上可以这样称呼它store.add_entry(&Entry{...})(即您可以传递对临时条目的引用)。此临时条目将超出范围/在语句之后。因此,Rust 不允许将它放入entries,因为它会指向一个已经删除(读取:无效)的值。

操场

  • OP 的解释可能会对**为什么**有所帮助。否则他们就会被货物邪教任意改变。 (2认同)