The `if` state remains borrowed in the body

I just stumbled upon some behavior in Rust (1.12) that I cannot explain. I have a structure that implements lazy loading using RefCell<Option<i32>>and a function to access data:

struct Foo {
    data: RefCell<Option<i32>>
}

impl Foo {
    fn get_data(&self) -> i32 {
        if self.data.borrow().is_none() { // <--- (a)
            let d = 1337;
            self.data.borrow_mut() = Some(d); // <--- (b)
            d
        } else {
            self.data.borrow().unwrap()
        }
    }
}

This compiles, but gives a runtime error: RefCellcomplains that the loan is already active when trying borrow_mutin line (b) . However, the problem does not occur if I modify the if statement as follows:

let is_none = self.data.borrow().is_none();
if is_none {

Question: Why is the loan in the if condition on line (a) still active inside the body of the if statement? is_none()Should n't the call end, as I only hold bool, not the borrowed value?

+4
1

.

, - . , .

, - Rust 1.13, , , , .

+5

Source: https://habr.com/ru/post/1660161/


All Articles