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

What you want is impossible. You'll have to write two functions (note that I replaced u16 with usize - there is no reason why you should limit yourself to 65536 characters per line):

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

fn row_mut(&mut self, index: usize) -> &mut Row {
    &mut self.rows[index]
}

Note that this is a common pattern across all Rust code. For example Vec has get(idx) and get_mut(idx).


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:

  • Your implementation would panic if index is out of bounds. The idiomatic way of handling this is to return an Option, which get and get_mut allow you to get for free.
  • Using u16 does not make much sense, as Vec is indexed using usize. Using u16 is arbitrary here unless you really want to provide hard-coded limitations. In that case, I wouldn't rely on the type's max value but a constant instead that would make the intent clearer.

Tags:

Rust