可变借入的吸气剂寿命不够长 [英] Mutable borrow in a getter not living long enough

查看:24
本文介绍了可变借入的吸气剂寿命不够长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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() {}

(游乐场)

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,但这是我从不同语言移植的一些代码,所以我没有执行任何目前正在重构(只是移植和覆盖测试).那里的终身问题是什么?

I didn't want to have the data field public, so I tried to use a getter. I know getters are not working well in Rust, and properly encapsulated collection shouldn't have a mutable get, but this is some code I'm porting from a different language, so I'm not performing any refactoring at the moment (just porting and covering with tests). What's the lifetime issue there?

推荐答案

With

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

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

the core issue is that the return type of data_mut() is already a &mut Data value, so you're essentially creating a &mut &mut Data, though that will collapse. The simplest fix in your case is to drop the &mut entirely

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

似乎通过添加 &mut 会导致借用检查器创建一个临时位置,然后引用该位置.

It would seem that by adding the &mut you're causing the borrow checker to create a temporary location and then take a reference to that location.

这篇关于可变借入的吸气剂寿命不够长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆