[英]“does not necessarily outlive the lifetime” issue
我的目標是擁有一個包含各種Entry
項目的Store
。 Entry
項目可以比 store 本身壽命更長,因此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) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
在這種情況下,錯誤 E0308不是很有幫助。
我不明白為什么add_entry
方法的生命周期必須比impl
的生命周期長,這是我從錯誤中理解的。
我確信這是非常基本的東西,但我無法通過閱讀Rust 編程語言直到第 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{...})
(即,您可以傳遞對臨時條目的引用)。 此臨時條目將 go 超出范圍/在語句之后。 因此, Rust 不允許將其放入entries
,因為它會指向已刪除(讀取:無效)的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.