gpt4 book ai didi

arrays - 如何在数组中添加一个值?

转载 作者:行者123 更新时间:2023-11-29 08:25:49 24 4
gpt4 key购买 nike

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

最佳答案

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

您更有可能需要 VecVec::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);
}

另见:

关于arrays - 如何在数组中添加一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59040549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com