How to delete element when iterating a vec?

To translate this into code, Vec::retain() works similarly¹ to this:

    let mut vecc = vec![1, 2, 3, 4];

    let mut idx_wr = 0usize;
    for idx_rd in 0..vecc.len() {
        if ! (vecc[idx_rd] == 1) {
            vecc.swap(idx_wr, idx_rd);
            idx_wr += 1;
        }
    }
    
    vecc.truncate(idx_wr);

¹ I haven't looked at the actual code for retain; it probably uses unsafe to perform a move instead of the swap call I used.

3 Likes