Why is borrow_mut able to infer the type and borrow can't?

I'm really puzzled, why is borrow giving compiler error and borrow_mut not?

use std::rc::Rc;
use std::{borrow::Borrow, cell::RefCell};
struct Human {
    age: i128,
    name: String,
}
impl Human {
    fn new(age: i128, name: &str) -> Self {
        Human {
            age,
            name: name.to_owned(),
        }
    }
}
impl Default for Human {
    fn default() -> Self {
        Human {
            age: 0,
            name: "".to_owned(),
        }
    }
}
fn main() {
    let rc = Rc::new(RefCell::new(Human::default()));
    let w = rc.borrow();//error here
    let w = rc.borrow_mut();//OK here
}

This happens because Rc implements Borrow trait while RefCell also has a borrow method. But only RefCell has a borrow_mut method. This is why the first one causes an error - because the compiler infers the wrong borrow. What you want is probably achieved by:

fn main() {
    let rc = Rc::new(RefCell::new(Human::default()));
    let w = RefCell::borrow(&rc);//error here
    let w = rc.borrow_mut();//OK here
}

Note that the way the code is written, it will cause a panic, because the RefCell is mutably borrowed while it is also immutably borrowed.

1 Like

In this case, since you don't intend to use Borrow::borrow but RefCell::borrow, simply delete the use of std::borrow::Borrow and it will compile.

1 Like

Thanks, really appreciate that detailed explanation.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.