rust - setter/getter 中的可变借用时间不够长

标签 rust borrow-checker

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 字段公开,所以我尝试使用 getter。我知道 getter 在 Rust 中不能很好地工作,并且正确封装的集合不应该有一个可变的 get,但这是我从不同语言移植的一些代码,所以我没有执行任何目前正在重构(只是移植和覆盖测试)。那里的生命周期问题是什么?

最佳答案

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

核心问题是 data_mut() 的返回类型已经是一个 &mut Data 值,所以你实际上是在创建一个 &mut &mut Data,尽管那会崩溃。在您的情况下,最简单的解决方法是完全删除 &mut

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

看起来,通过添加 &mut,您会导致借用检查器创建一个临时位置,然后引用该位置。

关于rust - setter/getter 中的可变借用时间不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51502717/

相关文章:

rust - 如何使用Rust fltk表示例绘制自己的字符串数组?

rust - "expected identifier"创建宏时同时定义可变变量

rust - 使用包含借用参数的结构

rust - 如何在没有目录部分的情况下获取当前程序的名称?

static - 从另一个静态方法调用 trait 静态方法 (rust)

rust - 从全局结构访问数据,出现错误 "borrowed value does not live long enough"

rust - 引用盒装值的生命周期不够长

rust - 如果我想将单个可变对象传递给函数的多个参数,我该怎么办?

rust - 对多个方法参数使用相同的引用

rust - 当在闭包中借用 self 时,使用静态生命周期会触发 "closure may outlive function"