0

I made a simple struct and implemented Default for it:

#[derive(Clone, Copy)]
struct LifeCell {
    state: usize
}

impl Default for LifeCell {
    fn default() -> LifeCell {
        LifeCell {
            state: 0
        }
    }
}

I'm trying to create an array of such structs:

const TOTAL_CELLS: usize = 20;
let mut new_field: [[LifeCell; TOTAL_CELLS]; TOTAL_CELLS] = Default::default();

This compiles okay until I set TOTAL_CELLS to 35. Then it doesn't compile with an error:

error[E0277]: the trait bound `[[LifeCell; 35]; 35]: std::default::Default` is not satisfied
  --> src/main.rs:14:65
   |
14 |     let mut new_field: [[LifeCell; TOTAL_CELLS]; TOTAL_CELLS] = Default::default();
   |                                                                 ^^^^^^^^^^^^^^^^ the trait `std::default::Default` is not implemented for `[[LifeCell; 35]; 35]`
   |
   = help: the following implementations were found:
             <&'a [T] as std::default::Default>
             <&'a mut [T] as std::default::Default>
             <[T; 32] as std::default::Default>
             <[T; 31] as std::default::Default>
           and 31 others
   = note: required by `std::default::Default::default`

I know the reason for it - at the moment, the Default trait is implemented only for array sizes up to 32. But what should I do if I need an array of structs that is bigger than that?

I'm using Rust 1.18.0.

6
  • This one, among many others, emerge from the fact that arrays only implement certain traits for sizes up to 32, including Default. Commented Jun 18, 2017 at 20:53
  • @E_net4 is there any way to do something like that then? Without heap allocation preferebly? Commented Jun 18, 2017 at 20:57
  • 1
    let mut new_field = [[LifeCell::default(); TOTAL_CELLS]; TOTAL_CELLS]; Commented Jun 18, 2017 at 21:52
  • @Shepmaster that does work, thank you! However, several problems arise afterwards with cloning that array and fitting it into another struct. Should I ask another question or update this one? Commented Jun 18, 2017 at 23:37
  • 1
    You can't clone the array for the same reasons and with the same workaround. I'm not sure what you mean by "fitting it into". However, I'd encourage you to not try to put this on the stack. The 35-cell version takes up 9800 bytes! That's a pretty huge thing to have on the stack, passing as arguments, returning, etc. Instead, heap allocate it once and then just pass around slices to it (&[[Cell; LEN]; LEN]). You could even use a single Vec of length LEN * LEN and abstract away the x/y mapping in a new type. Commented Jun 19, 2017 at 2:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.