I want to implement a binary tree. My main language is C++ so the code is probably not idiomatic Rust, but compiling the following code:
use std::rc::Rc;
struct Node {
left: Option<Rc<Node>>,
right: Option<Rc<Node>>,
data: String,
}
impl Node {
fn new(_data: String) -> Node {
Node {
data : _data.clone(),
left : None,
right : None,
}
}
fn insert_left(&mut self, mut node: &Rc<Node>) {
self.left = Some(node.clone());
}
fn insert_right(&mut self, mut node: &Rc<Node>) {
self.left = Some(node.clone());
}
}
fn main() {
let mut root = Rc::new(Node::new(String::from("root")));
let mut left = Rc::new(Node::new(String::from("left")));
root.insert_left(&left);
}
I have the compilation error:
error: cannot borrow immutable borrowed content as mutable
--> so.rs:31:9
|
31 | root.insert_left(&left);
| ^^^^
error: aborting due to previous error
I can't understand what is wrong here. After some try-mistake iterations I found out that problem lies in the insert_left()
function: if self
is an immutable reference, then it compiles with commented out content, but an immutable reference does not allow my to accomplish my goal.