2

How can I initialize an integer array [i32; 100] with the default value of i32 (0) by deriving the Default trait? I wrote this code:

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

But the compiler rejects it with this error:

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)
0

1 Answer 1

2

Default is currently only implemented for arrays of T: Default up to a length of 32. This is a historical restriction from before Rust had const generics, so the compiler could not cover multiple array lengths with a single implementation.

There is an open issue in the Rust repo (Use const generics for array Default impl) to impl [T; N]: Default for any N, but as of 2024 this is a work in progress.

You will have to manually implement Default for your struct:

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

impl Default for A {
    fn default() -> Self {
        A {
            a: Default::default(),
            arr: [Default::default(); 100],
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.