如何在鲁斯特不同大小的阵列之间进行复制

如何在鲁斯特不同大小的阵列之间进行复制

本文介绍了如何在鲁斯特不同大小的阵列之间进行复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有不同大小的两个数组:

If I have two arrays of different sizes:

let mut array1 = [0; 8];
let array2 = [1, 2, 3, 4];

我将如何复制数组2 进入前4个字节数组1 的?我可以把数组1的可变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.mut_iter().zip(array2.iter()) {
    *place = *data
}

创建,也就是可变指向引用到片/阵列。 不相同,但与。 需要两个迭代器和步骤,对他们在锁步,产生从两个元素作为一个元组(并尽快停止,因为任何一个停止工作)。

.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).

如果您需要/想写入发生之前做任何事情花哨的数据这是使用的方法。

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(数组2)

,虽然你将需要修剪两个数组,因为 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));

(如果你知道数组1 数组2 永远不再那么字节:: copy_memory(array1.mut_slice_to(array2.len()),数组2)应该也行。)

(If you know that array1 is always longer than array2 then bytes::copy_memory(array1.mut_slice_to(array2.len()), array2) should also work.)

目前,在字节版本优化了最好的,下降到的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.

这篇关于如何在鲁斯特不同大小的阵列之间进行复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:29