`use of moved value` on mutable reference in a loop
⚓ Rust 📅 2026-04-08 👤 surdeus 👁️ 6I am working on implementing matrices and I want the row_reduce and invert to use an inner function to reduce repetition and the way I'm thinking of doing this is by passing the original matrix by mutable reference and and optional second matrix to perform the same row operations on. The issue I ran into is that when I want to execute row operations on the optional matrix I get an error saying:
use of moved value move occurs because value has type `&mut Matrix<T>`, which does not implement the `Copy`
My code looks like this
fn row_reduce(matrix: &mut Matrix<T>, other: &mut Matrix<T> {
let mut row = 0;
let mut col = 0;
while col < matrix.cols && row < matrix.rows {
if let Some(k) = (row..self.rows).find(|&y| !matrix[(col, y)].is_zero()) {
matrix.swap_rows(row, k);
if let Some(other) = other {
\\ ^^^^^ error occurs here
other.swap_rows(row, k);
}
let pivot_value = matrix[(col, row)].clone();
matrix.divide_row(row, &pivot_value);
if let Some(other) = other {
other.divide_row(row, &pivot_value);
}
for y in 0..rows {
if row == y {
continue;
}
let factor = matrix[(row, y)].clone();
self.sub_scaled_row(row, y, &factor);
if let Some(other) = other {
other.divide_row(row, &pivot_value);
}
}
row += 1;
}
col += 1;
}
}
I can fix this by changing the function to work like this
fn row_reduce(matrix: &mut Matrix,<T> mut other: Option<&mut Matrix<T>>) {
...
if let Some(taken_other) = other.take() {
// do row operation
other = Some(taken_other)
}
}
However this feels clunky and I feel like there should not be a problem with using / borrowing a mutable reference like this in a loop because the (inner) reference only lasts for the if let section and the lifetime is dropped between every iteration of the loop. Is there a scenario where that would be invalid (specifically where the 'moved' reference only lasts for the lifetime of the loop), is there a reason why it can't be done by the compiler, or would it just be difficult to get the compiler to do?
I'm not necessarily asking for this specific use-case because I've found a workaround but I am asking to better understand the borrow checker and how the compiler works.
2 posts - 2 participants
🏷️ Rust_feed