rust

cannot borrow as mutable, as it is behind a `&` reference


In order to get to know Rust a bit better, I am building a simple text editor and have the following structs:

struct File {
    rows: Vec<Row>,
    filename: Option<String>
}

impl File {
    fn row(&self, index: u16) -> &Row{
        &self.rows[index as usize]
    }

}

struct Row {
    string: String,
}

struct EditorState {
    file: File,
}

As you can see, I am keeping the state of an editor in a struct, which references the file, which contains a number of rows, which contains a string (Each of these structs has more fields, but I have removed the ones not relevant to the problem)

Now I want to make my rows editable and added this:

impl Row {
    fn insert(&mut self, at: u16, c: char) {
        let at = at as usize;
        if at >= self.string.len() {
            self.string.push(c);
        } else {
            self.string.insert(at, c)
        }
    }
}

This is how I try to update the row:

//In the actual functon, I am capturing the keypress,
//get the correct row from the state and pass it and the pressed
// char to row.insert
fn update_row(mut state: &mut EditorState)  {
    let row = &state.file.row(0);
    row.insert(0, 'a');
}

This fails to compile:

error[E0596]: cannot borrow `*row` as mutable, as it is behind a `&` reference

From the error, I can see that the issue is that Row should be mutable so I can edit it (which makes sense, since I am mutating it's String). I can't figure out a) how to be able to mutate the string here, and b) how to do this without having row always return a mutable reference, as in all other cases, I am calling row to read a row, and not to write it.


Solution

  • Here is a more idiomatic implementation for File:

    impl File {
        fn row(&self, index: usize) -> Option<&Row> {
            self.rows.get(index)
        }
    
        fn row_mut(&mut self, index: usize) -> Option<&mut Row> {
            self.rows.get_mut(index)
        }
    }
    

    Items of note here: