首页 > 解决方案 > 具有引用和引用返回的结构:由于需求冲突,无法推断出 autoref 的适当生命周期

问题描述

在下面的代码中,我了解到在返回的引用Storage::insertConsumer<'a>. 但是,我遇到了麻烦:

  1. 理解为什么会发生这种冲突——也就是说,两者Consumer::storage都有Consumer::current_value相同的生命周期,那么 Rust 推断出的其他生命周期是什么?<'a>

  2. 如何最好地指定生命周期以及为什么这样做

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

我已阅读以下内容,但不确定我是否遵循它们如何适用于我的问题(也许他们这样做了,而我只是没有正确阅读):

标签: rustlifetime

解决方案


推荐阅读