Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into Rust array in place, push other elements down

Tags:

rust

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.

like image 338
Camden Clark Avatar asked Oct 18 '25 11:10

Camden Clark


1 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!

like image 132
alephalpha Avatar answered Oct 20 '25 23:10

alephalpha