Ziv*_*iva 9 arrays prepend rust
是否可以在数组前面添加一个值?我知道如何连接两个数组,但如果我有一个数组和一个值(与数组类型相同),我可以将此元素添加到数组前面吗?
在稳定的 Rust 中没有办法做到这一点;数组不能在运行时添加或删除值;它们的长度在编译时是固定的。
\n\xe2\x80\x99s 更有可能你想要一个Vec和Vec::insert。
也可以看看:
\n\n在 nightly Rust 中,您可以使用不稳定的功能来构造一个稍微大一点的全新数组,并将所有值移过去:
\n// 1.52.0-nightly (2021-03-07 234781afe33d3f339b00)\n#![allow(incomplete_features)]\n#![feature(const_generics, const_evaluatable_checked)]\n\nuse std::{\n array::IntoIter,\n mem::{self, MaybeUninit},\n ptr,\n};\n\nfn prepend<T, const N: usize>(a: [T; N], v: T) -> [T; N + 1] {\n // # SAFETY\n //\n // Converting an uninitialized array to an array of\n // uninitialized values is always safe.\n // https://github.com/rust-lang/rust/issues/80908\n let mut xs: [MaybeUninit<T>; N + 1] = unsafe { MaybeUninit::uninit().assume_init() };\n\n let (head, tail) = xs.split_first_mut().unwrap();\n *head = MaybeUninit::new(v);\n for (x, v) in tail.iter_mut().zip(IntoIter::new(a)) {\n *x = MaybeUninit::new(v)\n }\n\n // # SAFETY\n //\n // We are effectively transmuting from an array of filled `MaybeUninit<T>` to\n // the array of `T`, but cannot actually use `transmute`:\n // https://github.com/rust-lang/rust/issues/61956\n unsafe {\n let tmp_xs = &mut xs as *mut [MaybeUninit<T>; N + 1] as *mut [T; N + 1];\n mem::forget(xs);\n ptr::read(tmp_xs)\n }\n}\n\nfn main() {\n let v = prepend([1, 2, 3], 4);\n assert_eq!([4, 1, 2, 3], v);\n}\nRun Code Online (Sandbox Code Playgroud)\n也可以看看:
\n\n| 归档时间: |
|
| 查看次数: |
26426 次 |
| 最近记录: |