Every now and then, I run into the same issue with borrowing (or not borrowing) mutable variables inside a loop, and I finally sat down and compiled a minimal example. As a result, the code is a little silly, but it is the shortest version that I could come up with that highlights the problem:
struct Association {
used: bool,
key: usize,
value: String,
}
impl Association {
fn new(key: usize, value: &str) -> Self {
Association{used: false, key: key, value: value.to_string()}
}
}
fn find_unused<'a>(data: &'a mut Vec<Association>) -> Option<&'a String> {
for k in 0.. {
for a in data {
if a.key == k && !a.used {
a.used = true;
return Some(&a.value);
}
}
}
None
}
fn main() {
let mut assoc = vec![
Association::new(7, "Hello"),
Association::new(9, "World")
];
println!("{}", find_unused(&mut assoc).unwrap());
println!("{}", find_unused(&mut assoc).unwrap());
}
This will fail with an error because data
was moved before. If I borrow it instead, it will fail because it was borrowed before. I would like to understand exactly what is happening and how to solve it in general. In particular, I do not want to change the structure of the code, even if it is silly. I do not want to implement a workaround, because this is just a minimal example: Please assume that the nesting of the loops is the "right" way to do it, even if it is utterly silly here, which it definitely is.
I would only like to know how to communicate to the borrow checker that what is happening here is actually ok. I know of one way to do this:
fn find_unused<'a>(data: &'a mut Vec<Association>) -> Option<&'a String> {
for k in 0.. {
for j in 0..data.len() {
if data[j].key == k && !data[j].used {
data[j].used = true;
return Some(&data[j].value);
}
}
}
None
}
This compiles without error and works as intended. In my naïve understanding, there should be a way to express the above with iterators instead of indexing, and I would like to know how that would be done.
-Zpolonius
. On the solution I give it was just to help you there is a way using iterator, you can't complain if you didn't create a minimal reproducible example that really show your use case. I'm not a magician.