如何克隆长度大于32的数组? [英] How to clone an array with length bigger than 32?

查看:119
本文介绍了如何克隆长度大于32的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本机类型(或实现Copy特征的类型)的定长数组可以在Rust中克隆,最大长度为32.即,编译:

A fixed-length array of a native type (or of a type that implements the Copy trait) can be cloned in Rust up to the length of 32. That is, this compiles:

fn main() {
    let source: [i32; 32] = [0; 32]; // length 32
    let _cloned = source.clone();
}

但这不是:

fn main() {
    let source: [i32; 33] = [0; 33]; // length 33
    let _cloned = source.clone(); // <-- compile error
}

实际上,特征Clone 仅为每个泛型声明一个方法数组长度,从0到32.

In fact, the trait Clone only declares a method for each generic array length, from 0 to 32.

克隆通用长度为33的通用数组的有效且惯用的方法是什么?

What is an efficient and idiomatic way to clone a generic array of length, say, 33?

推荐答案

您不能在自己的代码中添加impl Clone.该问题将在某个时候得到解决,与此同时,您通常可以通过不同的努力来解决该问题:

You can't add the impl Clone in your own code. This problem will be fixed at some point, in the mean time you can mostly work around it with varying amount of effort:

  • 如果您只有一个具体类型的局部变量,并且类型为Copy(如您的示例所示),则可以简单地 copy 而不是 cloning ,即let _cloned = source;.
  • 如果数组是您要为其实现Clone的结构的一个字段(并且derive将不起作用),您仍然可以手动实现Clone并在实现中使用上述技巧.
  • li>
  • 克隆非Copy类型的数组比较麻烦,因为Clone可能会失败.您可以根据需要多次写出[x[0].clone(), x[1].clone(), ...],这是很多工作,但至少可以肯定是正确的.
  • 如果其他所有方法均失败,则仍然可以创建新包装.这需要很多样板来委派您需要的所有其他特征,但是您可以(再次手动)实现Clone.
  • If you just have a local variable of a concrete type and the type is Copy (as in your example), you can simply copy rather than cloning, i.e., let _cloned = source;.
  • If the array is a field of a struct you want to implement Clone for (and derive won't work), you can still manually implement Clone and using the above trick in the implementation.
  • Cloning an array of non-Copy types is trickier, because Clone can fail. You could write out [x[0].clone(), x[1].clone(), ...] for as many times as you need, it's a lot of work but at least it's certain to be correct.
  • If all else fails, you can still create a newtype wrapper. This requires quite a bit of boilerplate to delegate all the other traits you need, but then you can (again, manually) implement Clone.

这篇关于如何克隆长度大于32的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆