arrays - 如何在数组的开头附加一个值?
问题描述
是否可以在数组的开头附加一个值?我知道如何连接两个数组,但是如果我有一个数组和一个值(与数组的类型相同),我可以将此元素附加到数组的开头吗?
解决方案
在稳定的 Rust 中没有办法做到这一点。数组不能在运行时添加或删除值;它们的长度在编译时是固定的。
你更有可能想要一个Vec
and Vec::insert
。
也可以看看:
在 nightly Rust 中,您可以使用不稳定的特性来构建一个稍微大一点的全新数组并将所有值移过来:
// 1.52.0-nightly (2021-03-07 234781afe33d3f339b00)
#![allow(incomplete_features)]
#![feature(const_generics, const_evaluatable_checked)]
use std::{
array::IntoIter,
mem::{self, MaybeUninit},
ptr,
};
fn prepend<T, const N: usize>(a: [T; N], v: T) -> [T; N + 1] {
// # SAFETY
//
// Converting an uninitialized array to an array of
// uninitialized values is always safe.
// https://github.com/rust-lang/rust/issues/80908
let mut xs: [MaybeUninit<T>; N + 1] = unsafe { MaybeUninit::uninit().assume_init() };
let (head, tail) = xs.split_first_mut().unwrap();
*head = MaybeUninit::new(v);
for (x, v) in tail.iter_mut().zip(IntoIter::new(a)) {
*x = MaybeUninit::new(v)
}
// # SAFETY
//
// We are effectively transmuting from an array of filled `MaybeUninit<T>` to
// the array of `T`, but cannot actually use `transmute`:
// https://github.com/rust-lang/rust/issues/61956
unsafe {
let tmp_xs = &mut xs as *mut [MaybeUninit<T>; N + 1] as *mut [T; N + 1];
mem::forget(xs);
ptr::read(tmp_xs)
}
}
fn main() {
let v = prepend([1, 2, 3], 4);
assert_eq!([4, 1, 2, 3], v);
}
也可以看看:
推荐阅读
- html - 我希望斜线在两个小盒子之间
- html - 对齐图像以适合封面背景图像的区域?
- node.js - 在 Puppeteer 中将变量作为参数传递给 $eval
- python - 带有矢量文本和数值数据的决策树
- vb.net - Webforms 错误显示了两个项目,尽管解决方案显示了一个项目
- sql - 在 SQL Unpivot 中包含列名
- c# - ASP.NET Core react - 将 Okta 选项从 ASP.NET Core 传递到 ReactJS 应用程序
- python - 任意进程的python进程间互斥锁
- android - Presigned APK 在 AOSP 构建中丢失签名
- python - 在 altair 中设置单个点标记的大小