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 onlyRefCell 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.