我正在尝试在 Rust 中执行以下操作,特别是使用数组(我不想在这里使用向量,并且希望在完成后将元素推出数组)。
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];
你如何实现insert_in_place?我认为有一种方法可以使用切片来做到这一点,但我仍在学习并想知道是否有一种真正优雅的方法来做这种事情。
最佳答案
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!或等效地:
fn insert_in_place<T>(array: &mut [T], value: T, index: usize) {
array[index..].rotate_right(1);
array[index] = value;
}
Try it online!
关于rust - 原地插入 Rust 数组,将其他元素向下推,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69939819/