In my problem I have a vectorbased computations that modifies its element based on the value of its other elements. The following example of a running sum may serve as a simplified toy problem:
#[derive(Copy, Clone)]
struct X{x:i16}
fn running_sum(a:&X, b:&X, c:&mut X) {
c.x = a.x + b.x;
}
fn main() {
const N: usize = 10
let mut row = [X{x:0};N];
for i in 0..N2 {
running_sum(&row[i], &row[i+1], &mut row[i+2]);
}
println!("{} {} {}", &row[0].x, &row[1].x, &row[2].x);
}
It simply evaluates x[i] = x[i1] + x[i2]. This obviously doesn't work, because:
error[E0502]: cannot borrow `row[_]` as mutable because it is also borrowed as immutable
> src/main.rs:11:35

11  running_sum(&row[0], &row[1], &mut row[2]);
   ^^^^^^^^^^^ mutable borrow occurs here
  
  immutable borrow occurs here
 immutable borrow later used by call
I fully understand the reason; the question is how to make it compile?
Please don't advice putting the c.x = a.x + b.x;
into the for
loop of the main program. This is exactly the situation I have now. In my real case that inner calculation involves a lot of math and I want to refactor it by breaking into parts.
The only solution (not specific to rust) that comes to my mind is to refactor running_sum()
into: running_sum(row: &mut &[X], pos: usize)
;
Any rustspecific solution that would solve the doubleborrow problem?