首页 > 解决方案 > 如何在数组的开头附加一个值?

问题描述

是否可以在数组的开头附加一个值?我知道如何连接两个数组,但是如果我有一个数组和一个值(与数组的类型相同),我可以将此元素附加到数组的开头吗?

标签: arraysrust

解决方案


在稳定的 Rust 中没有办法做到这一点。数组不能在运行时添加或删除值;它们的长度在编译时是固定的。

你更有可能想要一个Vecand 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);
}

也可以看看:


推荐阅读