Nick Klavohn
Nick Klavohn

Reputation: 35

Why does the Rust borrow checker treat RefMut<T> differently than T or &mut T?

When I have a struct or a mutable reference to a struct, I can simultaneously pass mutable references to multiple of its fields into a function. The borrow checker is okay with this.

However, if I have a mut RefMut<struct>, this behavior is no longer allowed. Specifically, the compiler error is "cannot borrow x as mutable more than once at a time".

I've attached a small reproducible sample below.

Can you explain why the borrow checker disallows the last example?

pub struct Test {
    pub a: f64,
    pub b: f64,
}

fn increment_both(a: &mut f64, b: &mut f64) {
    *a += 1.0;
    *b += 1.0;
}

pub fn example() {
    // allowed
    let mut t = Test { a: 0.0, b: 0.0 };
    increment_both(&mut t.a, &mut t.b);

    // allowed
    let t_ref = &mut t;
    increment_both(&mut t_ref.a, &mut t_ref.b);

    // disallowed
    let ref_cell = RefCell::new(t);
    let mut t_rcell = ref_cell.borrow_mut();
    increment_both(&mut t_rcell.a, &mut t_rcell.b);
}

Upvotes: 0

Views: 51

Answers (0)

Related Questions