Hi,
I'm playing with writing a n-body simulation in Rust, just for practicing. In the code I need to compute the pairwise acting forces between to bodies. The bodies are stored in a vector of body-structs. However, the way I attempt it the borrow checker (rightfully) complains.
I have a simple testcode (Playground:
#[derive(Debug)]
struct Foo {
val: i32,
sum: i32
}
impl Foo {
fn new(i: i32) -> Self {
Foo {val: i, sum: 0}
}
}
fn my_op(a: &mut Foo, b: &mut Foo) {
a.sum = a.val + b.val;
b.sum = a.val - b.val;
}
fn main() {
let mut list:Vec<Foo> = Vec::new();
for i in 0..3 {
list.push(Foo::new(i));
}
println!("{:?}", list);
for i in 0..list.len()-1 {
for j in i+1..list.len() {
my_op(&mut list[i], &mut list[j]);
}
}
println!("{:?}", list);
}
As you can see I try to apply my_op
to two elements from the vector, which cannot be equal due to the design of the nested loop indices (which the borrow checker does not seem to notice). I tried to work with iterators instead of nested loops to make it easier for the borrow checker, but I could not find any fitting method. How would you suggest I do this properly.
Thanks for your help