GoatPonny
GoatPonny

Reputation: 87

Rust nested fors itering over the same vector

I was trying to change some of vector elements, while itering over the vector.

for operator in operators {
    // add left side
    let node = nodes[operator.index-1].clone();
    nodes[operator.index].children.push(node);

    // add right side
    let node = nodes[operator.index+1].clone();
    nodes[operator.index].children.push(node);

    // remove used nodes
    nodes.remove(operator.index+1);
    nodes.remove(operator.index-1);

    // two items were removed, so every index higher than the current one needs to be lowered by 2
    for operator2 in &mut operators {
        if operator2.index > operator.index {
            operator2.index -= 2;
        }
    }
}

Sadly this isn't possible in rust, because error says that 'operators' was moved. I tried to change for to look like this: for operator in &operators, but then it has problem getting 'operators' as mutable and immutable at the same time. What can I do to make it work?

Upvotes: 0

Views: 60

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71380

Use simple loops with indices:

for operator_idx in 0..operators.len() {
    let operator = &operators[operator_idx];

    // add left side
    let node = nodes[operator.index-1].clone();
    nodes[operator.index].children.push(node);

    // add right side
    let node = nodes[operator.index+1].clone();
    nodes[operator.index].children.push(node);

    // remove used nodes
    nodes.remove(operator.index+1);
    nodes.remove(operator.index-1);

    // two items were removed, so every index higher than the current one needs to be lowered by 2
    for operator2 in &mut operators {
        if operator2.index > operator.index {
            operator2.index -= 2;
        }
    }
}

Upvotes: 1

Related Questions