建议如何声明包含数组的结构,然后创建一个零初始化实例?
以下是结构:
#[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
我做错了什么吗?
发布于 2014-11-21 13:56:29
恐怕您不能这样做,您需要自己为您的结构实现Default
:
struct Histogram {
sum: u32,
bins: [u32; 256],
}
impl Default for Histogram {
#[inline]
fn default() -> Histogram {
Histogram {
sum: 0,
bins: [0; 256],
}
}
}
数值类型与这种情况无关,它更像是固定大小数组的问题。他们仍然需要通用的数字文字来支持这类事物。
发布于 2015-03-28 12:36:30
如果您肯定要用零初始化每个字段,这将起作用:
impl Default for Histogram {
fn default() -> Histogram {
unsafe { std::mem::zeroed() }
}
}
发布于 2014-11-21 14:00:24
实际上,在编写本报告时,对固定长度数组的支持仍在标准库中被散列:
https://stackoverflow.com/questions/27062874
复制相似问题