![](/img/trans.png)
[英]Does std::array default-initialize or value-initialize?
[英]How to default-initialize a struct containing an array in Rust?
声明包含数组的结构,然后创建零初始化实例的推荐方法是什么?
这是结构:
#[derive(Default)]
struct Histogram {
sum: u32,
bins: [u32; 256],
}
和编译器错误:
error[E0277]: the trait bound `[u32; 256]: std::default::Default` is not satisfied
--> src/lib.rs:4:5
|
4 | bins: [u32; 256],
| ^^^^^^^^^^^^^^^^ the trait `std::default::Default` is not implemented for `[u32; 256]`
|
= help: the following implementations were found:
<[T; 14] as std::default::Default>
<&'a [T] as std::default::Default>
<[T; 22] as std::default::Default>
<[T; 7] as std::default::Default>
and 31 others
= note: required by `std::default::Default::default`
如果我尝试为数组添加缺少的初始值设定项:
impl Default for [u32; 256] {
fn default() -> [u32; 255] {
[0; 256]
}
}
我明白了:
error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> src/lib.rs:7:5
|
7 | impl Default for [u32; 256] {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ impl doesn't use types inside crate
|
= note: the impl does not reference any types defined in this crate
= note: define and implement a trait or new type instead
难道我做错了什么?
Rust没有为所有数组实现Default
,因为它没有非类型多态。 因此, Default
仅针对少数大小实现。
但是,您可以为您的类型实现默认值:
impl Default for Histogram {
fn default() -> Histogram {
Histogram {
sum: 0,
bins: [0; 256],
}
}
}
注意:我认为为u32
实现Default
是很可疑的; 为什么0
而不是1
? 还是42
? 没有好的答案,所以没有明显的默认。
我担心你不能这样做,你需要自己为你的结构实现Default
:
struct Histogram {
sum: u32,
bins: [u32; 256],
}
impl Default for Histogram {
#[inline]
fn default() -> Histogram {
Histogram {
sum: 0,
bins: [0; 256],
}
}
}
数字类型与此情况无关,更像是固定大小数组的问题。 他们仍然需要通用的数字文字来本地支持这种事情。
如果你确定用零初始化每个字段,这将起作用:
impl Default for Histogram {
fn default() -> Histogram {
unsafe { std::mem::zeroed() }
}
}
实际上,在撰写本文时,标准库中仍然支持对固定长度数组的支持:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.