如何在Rust中默认初始化包含数组的结构?

And*_*ner 8 arrays struct initializer rust

声明包含数组的结构,然后创建零初始化实例的推荐方法是什么?

这是结构:

#[derive(Default)]
struct Histogram {
    sum: u32,
    bins: [u32; 256],
}
Run Code Online (Sandbox Code Playgroud)

和编译器错误:

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`
Run Code Online (Sandbox Code Playgroud)

如果我尝试为数组添加缺少的初始值设定项:

impl Default for [u32; 256] {
    fn default() -> [u32; 255] {
        [0; 256]
    }
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

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
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么?

Mat*_* M. 6

Rust没有Default为所有数组实现,因为它没有非类型多态.因此,Default仅针对少数尺寸实施.

但是,您可以为您的类型实现默认值:

impl Default for Histogram {
    fn default() -> Histogram {
        Histogram {
            sum: 0,
            bins: [0; 256],
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注:我主张实施Defaultu32是腥下手; 为什么01呢?还是42?没有好的答案,所以没有明显的默认.


Vla*_*eev 6

恐怕你不能这样做,你需要Default自己为你的结构实现:

struct Histogram {
    sum: u32,
    bins: [u32; 256],
}

impl Default for Histogram {
    #[inline]
    fn default() -> Histogram {
        Histogram {
            sum: 0,
            bins: [0; 256],
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

数字类型与这种情况无关,它更像是固定大小数组的问题。他们仍然需要通用数字文字来支持这种原生的东西。