gpt4 book ai didi

rust - "does not necessarily outlive the lifetime"问题

转载 作者:行者123 更新时间:2023-12-03 11:40:36 27 4
gpt4 key购买 nike

我的目标是拥有一个 Store其中包含各种 Entry项目。 Entry元素可以比商店本身生命周期更长,所以 Store保持 Vec<&Entry> ( playground ):

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);
}
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) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Error E0308在这种情况下不是很有帮助。

我不明白为什么生命周期在 add_entry方法必须长于 impl 之一,这是我从错误中了解到的。

我确信这是非常基础的东西,但我无法通过阅读 The Rust Programming Language 直到第 15 章来理解它。

最佳答案

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

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

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

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

Playground

关于rust - "does not necessarily outlive the lifetime"问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66244743/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com