rust - 原地插入 Rust 数组,将其他元素向下推

标签 rust

我正在尝试在 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/

相关文章:

rust - 我应该如何使用 i32 调用 Vec::with_capacity?

rust - 有什么方法可以迭代关联的常量吗?

rust diesel-cli 为不同的环境设置多个 env 文件

generics - 如何将泛型指定为 "don' t care”?

macros - Rust 宏可以处理多层嵌套表达式吗?

rust - 编写包含字符串并可在常量中使用的 Rust 结构类型

arrays - 我怎样才能拥有 Any 类型的数组?

unit-testing - 在宏上下文测试中使用 panic::catch_unwind 以解决单元测试中的 panic 问题

haskell - 在 Rust 中实现类似 Haskell 的素数迭代器

reference - 为什么要使用对 i32 的不可变引用