Mutable borrow in a getter not living long enough

后端 未结 1 1099
北恋
北恋 2020-12-21 09:33
pub type Data = i32;

pub struct Foo {
    data: Data,
}

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

pub         


        
相关标签:
1条回答
  • 2020-12-21 09:48

    With

    pub fn broken(&mut self) -> &mut Data {
        &mut self.foos.first_mut().unwrap().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()
    }
    

    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.

    0 讨论(0)
提交回复
热议问题