在下面的代码中,我了解到Storage::insert
返回的引用和Consumer<'a>
的生存期之间似乎存在生命周期冲突。但是,我遇到了麻烦:
了解为什么会发生这种冲突-即Consumer::storage
和Consumer::current_value
具有相同的生存期,因此Rust推论的其他生存期与<'a>
冲突< / p>
如何最好地指定生命周期以及为何有效
struct Storage {
value: i64,
}
impl Storage {
fn new() -> Self {
Storage { value: 0 }
}
fn insert(&mut self, v: i64) -> &i64 {
self.value = v;
&self.value
}
}
struct Consumer<'a> {
storage: &'a mut Storage,
current_value: &'a i64,
}
impl<'a> Consumer<'a> {
fn new(s: &'a mut Storage) -> Self {
Consumer {
storage: s,
current_value: &s.value,
}
}
fn new_value(&mut self, v: i64) {
self.current_value = self.storage.insert(v);
}
}
此代码导致的错误是:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/lib.rs:30:43
|
30 | self.current_value = self.storage.insert(v);
| ^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 29:5...
--> src/lib.rs:29:5
|
29 | / fn new_value(&mut self, v: i64) {
30 | | self.current_value = self.storage.insert(v);
31 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:30:30
|
30 | self.current_value = self.storage.insert(v);
| ^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 21:6...
--> src/lib.rs:21:6
|
21 | impl<'a> Consumer<'a> {
| ^^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:30:30
|
30 | self.current_value = self.storage.insert(v);
| ^^^^^^^^^^^^^^^^^^^^^^
我已经阅读了以下内容,但不确定是否遵循它们如何应用于我的问题(也许他们这样做了,而我只是阅读不正确):