用非复制类型初始化一个大的、固定大小的数组 [英] Initialize a large, fixed-size array with non-Copy types
问题描述
我正在尝试初始化一些可空、不可复制类型的固定大小数组,例如用于某种 Thing
的 Option
代码>.我想将其中的两个打包到一个结构中,而不需要任何额外的间接访问.我想写这样的东西:
I’m trying to initialize a fixed-size array of some nullable, non-copyable type, like an Option<Box<Thing>>
for some kind of Thing
. I’d like to pack two of them into a struct without any extra indirection. I’d like to write something like this:
let array: [Option<Box<Thing>>; SIZE] = [None; SIZE];
但是它不起作用,因为 [e;n]
语法要求 e
实现 Copy
.当然,我可以将其扩展为 SIZE
None
,但是当 SIZE
很大时,这可能很笨拙.我不相信这可以用一个没有 SIZE
的不自然编码的宏来完成.有什么好的办法吗?
But it doesn’t work because the [e; n]
syntax requires that e
implements Copy
. Of course, I could expand it into SIZE
None
s, but that can be unwieldy when SIZE
is large. I don’t believe this can be done with a macro without an unnatural encoding of SIZE
. Is there a good way to do it?
是的,使用 unsafe
这很容易;有没有没有unsafe
的方法?
Yes, this is easy with unsafe
; is there a way to do it without unsafe
?
推荐答案
你可以使用 Default
trait 用默认值初始化数组:
You could use the Default
trait to initialize the array with default values:
let array: [Option<Box<Thing>>; SIZE] = Default::default();
查看这个游乐场例子.
请注意,这仅适用于最多包含 32 个元素的数组,因为 Default::default
仅适用于最多 [T;32]
.参见 https://doc.rust-lang.org/std/default/trait.Default.html#impl-Default-98
Note that this will only work for arrays with up to 32 elements, because Default::default
is only implemented for up to [T; 32]
. See https://doc.rust-lang.org/std/default/trait.Default.html#impl-Default-98
这篇关于用非复制类型初始化一个大的、固定大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!