I’m trying to figure out exactly why I get this compile error in this very simple code;
cannot borrow
p
as mutable more than once at a time
as I do not store p more than once mutably; either directly or indirectly, as far as i can see.
fn main() {
println!("Running...");
let a = Element {
tag_name: String::from("p"),
parent_node: None,
};
let b = Element {
tag_name: String::from("p"),
parent_node: None,
};
let mut p = Node {
id: String::from("id-p"),
first_child: None,
};
p.append_child(a);
p.append_child(b);
}
struct Element<'a> {
tag_name: String,
parent_node: Option<&'a Node<'a>>,
}
impl Element<'_> {
// ..more to come..
}
struct Node<'a> {
id: String,
first_child: Option<Box<Element<'a>>>,
}
impl<'a> Node<'a> {
fn append_child(&'a mut self, node: Element<'a>) {
let node = Some(Box::new(node));
self.first_child = node
}
}
The second call to append_child is the problem, even tho the first call doesn’t create any references to self. Neither is anything returned from append_child.
If I removed the parent_node field from Element (and all the associated lifetime annotations), the problem goes away, even tho I never assigned to it;
fn main() {
println!("Running...");
let a = Element {
tag_name: String::from("p"),
// parent_node: None,
};
let b = Element {
tag_name: String::from("p"),
// parent_node: None,
};
let mut p = Node {
id: String::from("id-p"),
first_child: None,
};
p.append_child(a);
p.append_child(b);
}
struct Element {
tag_name: String,
// parent_node: Option<&'a Node<'a>>,
}
impl Element {
// ..more to come..
}
struct Node {
id: String,
first_child: Option<Box<Element>>,
}
impl Node {
fn append_child(& mut self, node: Element) {
let node = Some(Box::new(node));
self.first_child = node
}
}
Is the compiler simply saying that, the mere existence of the parent_node field ‘could’ store a reference to self, therefore creating this compile time problem?