This Rust program tries to set each number in a list to the sum of all numbers in the list that are factors of it:
fn main() {
let mut values = vec![1, 2, 3, 4];
for va in &mut values {
let mut cva = *va;
for vb in &values {
if (cva % *vb == 0) {
cva += *vb;
}
}
*va = cva;
}
println!("{:?}", values);
}
It does not build:
error[E0502]: cannot borrow `values` as immutable because it is also borrowed as mutable
--> src/main.rs:6:19
|
4 | for va in &mut values {
| -----------
| |
| mutable borrow occurs here
| mutable borrow later used here
5 | let mut cva = *va;
6 | for vb in &values {
| ^^^^^^^ immutable borrow occurs here
The code works fine if an index-based loop is used over va
:
fn main() {
let mut values = vec![1, 2, 3, 4];
for iva in 0..values.len() {
let mut cva = values[iva];
for vb in &values {
if (cva % *vb == 0) {
cva += *vb;
}
}
values[iva] = cva;
}
println!("{:?}", values);
}
This is rather awkward, as it requires the programmer to write values[iva]
over and over again instead of just va
, but with no apparent difference in formality or functionality, just a lexical search-and-replace. Is there a better way to write the first loop to avoid this?