getter 中的可变借用时间不够长

Mutable borrow in a getter not living long enough

pub type Data = i32;

pub struct Foo {
    data: Data,
}

impl Foo {
    pub fn data_mut(&mut self) -> &mut Data {
        &mut self.data
    }
}

pub struct Context {
    data: Data,
    foos: Vec<Foo>,
}

impl Context {
    pub fn broken(&mut self) -> &mut Data {
        // What are the lifetimes here that make this version not work?
        &mut self.foos.first_mut().unwrap().data_mut()
    }

    pub fn working(&mut self) -> &mut Data {
        &mut self.foos.first_mut().unwrap().data
    }
}

fn main() {}

(Playground)

error[E0597]: borrowed value does not live long enough
  --> src/main.rs:21:14
   |
21 |         &mut self.foos.first_mut().unwrap().data_mut()
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ temporary value does not live long enough
22 |     }
   |     - temporary value only lives until here
   |
note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 19:5...
  --> src/main.rs:19:5
   |
19 | /     pub fn broken(&mut self) -> &mut Data {
20 | |         // What are the lifetimes here that make this version not work?
21 | |         &mut self.foos.first_mut().unwrap().data_mut()
22 | |     }
   | |_____^

我不想使用 data 字段 public,所以我尝试使用 getter。我知道 getters 在 Rust 中不能很好地工作,并且正确封装的集合不应该有一个可变的 get,但这是我从不同语言移植的一些代码,所以我不是现在执行任何重构(只是移植和覆盖测试)。那里的寿命问题是什么?

pub fn broken(&mut self) -> &mut Data {
    &mut self.foos.first_mut().unwrap().data_mut()
}

核心问题是 data_mut() 的 return 类型已经是一个 &mut Data 值,因此您实质上是在创建一个 &mut &mut Data,尽管这会崩溃.在您的情况下,最简单的解决方法是完全删除 &mut

pub fn broken(&mut self) -> &mut Data {
    self.foos.first_mut().unwrap().data_mut()
}

似乎通过添加 &mut 可以让借用检查器创建一个临时位置,然后引用该位置。