如何在 Rust 中不同大小的数组之间进行复制? [英] How do you copy between arrays of different sizes in Rust?
问题描述
如果我有两个不同大小的数组:
If I have two arrays of different sizes:
let mut array1 = [0; 8];
let array2 = [1, 2, 3, 4];
如何将 array2
复制到 array1
的前 4 个字节中?我可以使用 array1 的可变 4 字节切片,但我不确定如何或是否可以分配给它.
How would I copy array2
into the first 4 bytes of array1
? I can take a mutable 4 byte slice of array1, but I'm not sure how or if I can assign into it.
推荐答案
最灵活的方式是使用迭代器依次处理每个元素:
The most flexible way is to use iterators to handle each element successively:
for (place, data) in array1.iter_mut().zip(array2.iter()) {
*place = *data
}
.mut_iter
创建 一个 Iterator
产生 &mut u8
,即指向切片/数组的可变引用.iter
与 共享引用 相同..zip
接受两个迭代器并以锁步方式遍历它们,将两者中的元素作为元组产生(并在任何一个停止时立即停止).
.mut_iter
creates an Iterator
that yields &mut u8
, that is, mutable references pointing into the slice/array. iter
does the same but with shared references. .zip
takes two iterators and steps over them in lock-step, yielding the elements from both as a tuple (and stops as soon as either one stops).
如果您需要/想要在写入 place
之前对数据做任何花哨的"操作,这就是可以使用的方法.
If you need/want to do anything 'fancy' with the data before writing to place
this is the approach to use.
但是,普通复制功能也作为单一方法提供,
However, the plain copying functionality is also provided as single methods,
.copy_from
,类似array1.copy_from(array2)
使用.
std::slice::bytes::copy_memory
,虽然您需要修剪两个数组,因为 copy_memory
要求它们的长度相同:
std::slice::bytes::copy_memory
, although you will need to trim the two arrays because copy_memory
requires they are the same length:
use std::cmp;
use std::slice::bytes;
let len = cmp::min(array1.len(), array2.len());
bytes::copy_memory(array1.mut_slice_to(len), array2.slice_to(len));
(如果你知道 array1
总是比 array2
长,那么 bytes::copy_memory(array1.mut_slice_to(array2.len()), array2)
也应该有效.)
(If you know that array1
is always longer than array2
then bytes::copy_memory(array1.mut_slice_to(array2.len()), array2)
should also work.)
目前,bytes
版本优化得最好,直到 memcpy
调用,但希望 rustc
/LLVM 改进最终会他们都这样.
At the moment, the bytes
version optimises the best, down to a memcpy
call, but hopefully rustc
/LLVM improvements will eventually take them all to that.
这篇关于如何在 Rust 中不同大小的数组之间进行复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!