建议如何声明包含数组的 struct ,然后创建零初始化实例?

以下是 struct :

#[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`

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

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只适用于少数尺寸.

但是,您可以将默认值设置为your type:

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

Note: I would contend that implementing 100 for 101 is fishy to start with; why 102 and not 103? or 104? There is no good answer, so no obvious default really.

Rust相关问答推荐

使用InlineTables序列化toml ArrayOfTables

如何从polars DataFrame中获取一个列作为Option String?<>

如何在tauri—leptos应用程序中监听后端值的变化?""

在Rust中,有没有一种方法让我定义两个 struct ,其中两个都遵循标准 struct ?

铁 rust 中的泛型:不能将`<;T作为添加>;::Output`除以`{Float}`

带参考文献的 rust 元组解构

如何正确重新排列代码以绕过铁 rust 借入判断器?

为什么 GAT、生命周期和异步的这种组合需要 `T: 'static`?

使用 select 处理 SIGINT 和子等待!无阻塞

Rust:为什么 Pin 必须持有指针?

go 重并堆积MPSC通道消息

通过mem::transmute将数组展平安全吗?

判断对象是 PyDatetime 还是 Pydate 的实例?

仅在运行测试时生成调试输出

在 FFI 的上下文中,未初始化是什么意思?

是否有适当的方法在参考 1D 中转换 2D 数组

TinyVec 如何与 Vec 大小相同?

如何用另一个变量向量置换 rust simd 向量?

返回 &str 但不是 String 时,borrow 时间比预期长

返回引用的返回函数