如何声明一个包含数组的结构体,并创建一个零初始化实例是推荐的方式?
这是结构体:
#[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]
}
}
I get:
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
我做错了什么吗?
[0;256]
将首先在堆栈/堆的某个位置被创建和初始化,然后移动到Histogram.bins
中。因此,大数组被移动,其中包括复制和丢弃。谢谢! - ch271828nHistogram
的元素为0,而无需逐个初始化。第三,根据调用者的情况,它可能永远不会实际生成结构体,甚至可能不会生成数组...如果给予机会,优化编译器可以进行惊人的转换。 - Matthieu M.