如何通过派生Default trait来初始化一个默认值为i32(0)的整数数组[i32; 100]?我写了这段代码:

#[derive(Default)]
struct A {
    a: i32,
    arr: [i32; 100],
}

但是编译器拒绝它,并返回以下错误:

error[E0277]: the trait bound `[i32; 100]: Default` is not satisfied
 --> src/main.rs:4:5
  |
1 | #[derive(Default)]
  |          ------- in this derive macro expansion
...
4 |     arr: [i32; 100],
  |     ^^^^^^^^^^^^^^^ the trait `Default` is not implemented for `[i32; 100]`
  |
  = help: the following other types implement trait `Default`:
            [T; 0]
            [T; 1]
            [T; 2]
            [T; 3]
            [T; 4]
            [T; 5]
            [T; 6]
            [T; 7]
          and 27 others
  = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info)

推荐答案

Default目前仅适用于长度最大为32的T: Defaultarray.这是Rust拥有常量泛型之前的历史限制,因此编译器不能使用单个实现覆盖多个数组长度.

Rust repo(Use const generics for array Default impl)中有一个开放的问题,要为任何N实现[T; N]: Default,但截至2024年,这是一个正在进行的工作.

您必须为您的 struct 手动实现Default:

struct A {
    a: i32,
    arr: [i32; 100],
}

impl Default for A {
    fn default() -> Self {
        A {
            a: Default::default(),
            arr: [Default::default(); 100],
        }
    }
}

Rust相关问答推荐

收集RangeInclusive T到Vec T<><>

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

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

如何修复数组中NewType导致的运行时开销

如果死 struct 实现了/派生了一些特征,为什么Rust会停止检测它们?

在铁 rust 中,如何一次只引用几件事中的一件?

Rust wasm 中的 Closure::new 和 Closure::wrap 有什么区别

我如何取消转义,在 Rust 中多次转义的字符串?

从光标位置旋转精灵

如何在 Rust 中将 Vec> 转换为 Vec>?

无法理解 Rust 对临时值的不可变和可变引用是如何被删除的

将原始可变指针传递给 C FFI 后出现意外值

使用 `clap` 在 Rust CLI 工具中设置布尔标志

为什么指定生命周期让我返回一个引用?

如何在 Rust 中返回通用 struct

如何存储返回 Future 的闭包列表并在 Rust 中的线程之间共享它?

将数据序列化为 struct 模型,其中两个字段的数据是根据 struct 中的其他字段计算的

为什么我可以从读取的可变自引用中移出?

为什么这里需要类型注解?

令人困惑的错误消息? (解包运算符)