-1

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 = &current_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 = &current_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

Playground

1
  • Alright, thanks for helping with the question. While creating an MRE I accidentally came to a solution to my problem. Question closed I guess
    – adamski234
    Commented Jun 3, 2020 at 20:28

1 Answer 1

0

I have figured it out. The issue is that I am trying to assign current_node inside a block borrowing that same variable. If you replace Some(current_node) with None it compiles

Not the answer you're looking for? Browse other questions tagged or ask your own question.