rust 如何在数组中前置一个值?

daolsyd0  于 2022-11-12  发布在  其他
关注(0)|答案(2)|浏览(137)

我知道如何连接两个数组,但是如果我有一个数组和一个值(与数组类型相同),我可以将这个元素前置到数组中吗?

gr8qqesn

gr8qqesn1#

在稳定的Rust中没有办法做到这一点;数组不能在运行时添加或删除值;它们的长度在编译时是固定的。
您更可能需要VecVec::insert
另请参阅:

在每夜的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);
}

另请参阅:

zbdgwd5y

zbdgwd5y2#

use phpify::array::array_unshift;

let mut queue = vec!["orange", "banana"];
array_unshift(&mut queue, "apple");

assert_eq!(queue, vec!["apple", "orange", "banana"]);

参考:https://docs.rs/phpify/0.1.0-beta4/phpify/array/index.html
另一种方法是在Rust中编写类似于https://stackoverflow.com/a/8963973/9676346的函数

相关问题