This question already has an answer here:
- How to idiomatically iterate one half of an array and modify the structure of the other? 1 answer
- How can I iterate a vector once and insert/remove/modify multiple elements along the way? 1 answer
- How can I modify a collection while also iterating over it? 2 answers
- Removing elements from a Vec based on some condition 2 answers
- Best way to remove elements of Vec depending on other elements of the same Vec 3 answers
I'm referring to the container itself, not the contents of the container. I want to insert, remove, append, etc. I made an abstraction of my problem below:
fn f() {
let mut numbers = vec![10, 11, 12, 14, 15];
for index in 0..numbers.len() {
process(numbers[index]);
if numbers[index] == 12 {
numbers.insert(index + 1);
}
}
}
Function f
would work, but the number of times it loops over the container does not change as the size of the container changes.
fn g() {
let mut numbers = vec![10, 11, 12, 14, 15];
for (index, num) in numbers.iter().enumerate() {
process(num);
if num == 12 {
numbers.insert(index + 1);
}
}
}
Function g
looks like the most idiomatic Rust way to do this, but it does not compile due to an illegal mutable borrow references occurring.
fn h() {
let mut numbers = vec![10, 11, 12, 14, 15];
let mut index = 0;
while index < numbers.len() {
process(numbers[index]);
if numbers[index] == 12 {
numbers.insert(index + 1);
}
index += 1;
}
}
Function h
is the only version that works but it does not seem like the right way to do it. I'm basically just simulating a C style for
loop with a while
loop. I'm hoping someone knows of a more succinct way of writing it, preferably with a for
loop instead.