Cannot borrow as mutable in loop variables

I get the following error, and I don't know why this is happening.

error[E0596]: cannot borrow data in a `&` reference as mutable
  --> src/lib.rs:27:29
   |
27 | / ...                   boards
28 | | ...                       .last()
29 | | ...                       .unwrap()
30 | | ...                       .insert(*num, (row, col));
   | |___________________________________________________^ cannot borrow as mutable

The following is my code:

let mut boards: Vec<HashMap<i32, (usize, usize)>> = vec![];
for line in file_it.lines() {
    if line.unwrap().is_empty() {
        boards.push(HashMap::new());
        for row in 0..5 {
            match file_it.read_line(&mut buf) {
                Ok(_) => {
                    let curr_row: Vec<i32> = buf
                                    .split_whitespace()
                                    .map(|num| num.trim().parse::<i32>().unwrap())
                                    .collect();
                    for (col, num) in curr_row.iter().enumerate() {
                        boards
                            .last()
                            .unwrap()
                            .insert(*num, (row, col));
                    }
                }
                Err(e) => println!("Error reading bingo board {}, Error: {}", boards.len(), e),
            }
        }
    }
}

Any suggestions to fix the above error, and why this error is happening would be greatly appreciated!

Call last_mut instead of last. The last() function returns an immutable reference to the last element, which cannot be used to modify it.

2 Likes

Thanks @alice !