Insert into Rust array in place, push other elements down

Viewed 919

I'm trying to do the following in Rust, specifically using arrays (I don't want to use vectors here, and want elements pushed out of the array if we're done).

let mut x = [1, 2, 3, 4, 5];
// array, number to insert, place to be inserted at
insert_in_place(&x, 7, 1);
// x is now [1, 7, 2, 3, 4];

How do you implement insert_in_place?

I think there's a way to do this using slices, but I'm still learning and wondering if there's a really elegant way to do this kind of thing.

2 Answers
fn insert_in_place<T>(array: &mut [T], value: T, index: usize) {
  *array.last_mut().unwrap() = value;
  array[index..].rotate_right(1);
}

Try it online!

Or equivalently:

fn insert_in_place<T>(array: &mut [T], value: T, index: usize) {
  array[index..].rotate_right(1);
  array[index] = value;
}

Try it online!

Iterate the slice, skipping elements before the index of the one you need to insert. Then swap each element with its previous element (or, for the first one, use the item to add).

fn insert_in_place<T>(x: &mut [T], new: T, index: usize) {
    let mut next = new;
    for e in x.iter_mut().skip(index) {
        std::mem::swap(e, &mut next);
    }
}

fn main() {
    let mut x = [1, 2, 3, 4, 5];
    // array, number to insert, place to be inserted at
    insert_in_place(&mut x, 7, 1);

    // x is now [1, 7, 2, 3, 4];
    println!("{:?}", x);
}
Related