I have a &mut
reference to a struct. I want to reassign a field of the referenced struct, but I only get cannot assign to current_node.parameter because it is borrowed
.
I have also tried let ref mut
in the current_node
declaration, but the same issue happened.
pub fn create_ars_tree() {
let mut top_level_node = NodeItem {
key: StringOrNodeItems::Text(String::new()),
parameter: StringOrNodeItems::Text(String::new()),
parent_item: None,
};
let mut current_node = &mut top_level_node; //Reference to the currently edited node
let mut current_part = ¤t_node.key; //Reference to the currently edited string
for current_char in "abcdef".chars() {
if current_char == '{' {
//Handle new opening bracket
match current_part {
StringOrNodeItems::Text(text) => {
current_node.key = StringOrNodeItems::Keys(vec![
NodeItem {
key: StringOrNodeItems::Text(text.to_string()),
parameter: StringOrNodeItems::Text(String::new()),
parent_item: Some(current_node)
//parent_item: None
}
]);
},
StringOrNodeItems::Keys(keys) => {
unimplemented!();
}
}
}
}
}
#[derive(Debug)]
pub struct NodeItem<'a> {
key: StringOrNodeItems<'a>,
parameter: StringOrNodeItems<'a>,
parent_item: Option<&'a NodeItem<'a>>,
}
#[derive(Debug)]
enum StringOrNodeItems<'a> {
Text(String),
Keys(Vec<NodeItem<'a>>),
}
Error:
error[E0506]: cannot assign to `current_node.key` because it is borrowed
--> src/lib.rs:14:6
|
8 | let mut current_part = ¤t_node.key; //Reference to the currently edited string
| ----------------- borrow of `current_node.key` occurs here
...
12 | match current_part {
| ------------ borrow later used here
13 | StringOrNodeItems::Text(text) => {
14 | current_node.key = StringOrNodeItems::Keys(vec![
| ^^^^^^^^^^^^^^^^ assignment to borrowed `current_node.key` occurs here