简体   繁体   English

克隆固定大小数组的最有效方法是什么?

[英]What is the most efficient way to clone a fixed-sized array?

I have a struct that consists of a fixed-size byte array with 65536 elements.我有一个结构,它由一个具有 65536 个元素的固定大小的字节数组组成。

I've implemented Clone on my struct naively — I create a new array and loop through the original, copying each element one-at-a-time.我实现了Clone对我的结构天真-我通过原创建一个新的数组和循环,复制一个-AT-A-时间每个元素。 Is there a more efficient or idiomatic way of doing this that would essentially boil down to a memcpy ?有没有更有效或惯用的方法来做到这一点,基本上可以归结为memcpy

Since Rust 1.21从 Rust 1.21 开始

Arrays of items that are Clone always implement Clone , so you can simply call .clone() on the array, or #[derive(Clone)] on the struct. Clone项的数组始终实现Clone ,因此您可以简单地在数组上调用.clone() ,或在结构上调用#[derive(Clone)]

Before Rust 1.21在 Rust 1.21 之前

As of Rust 1.12, arrays only implement Clone for up to 32 items.从 Rust 1.12 开始,数组只为最多 32 个项目实现Clone However, arrays implement Copy for any number of items (despite Copy requiring Clone !).但是,数组为任意数量的项目实现了Copy (尽管Copy需要Clone !)。 We can therefore make an implicit copy of the array in our implementation of Clone .因此,我们可以在Clone的实现中创建数组的隐式副本。

struct Foo {
    b: [u8; 65536],
}

impl Clone for Foo {
    fn clone(&self) -> Self {
        Foo {
            b: self.b
        }
    }
}

If you also want your struct to implement Copy , then you can also implement Clone::clone by just making a copy of self :如果您还希望您的结构实现Copy ,那么您也可以通过制作self的副本来实现Clone::clone

#[derive(Copy)]
struct Foo {
    b: [u8; 65536],
}

impl Clone for Foo {
    fn clone(&self) -> Self {
        *self
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM