Cannot default() slices bigger than 32 items


#1

This code works as expected

#[repr(C)]
#[derive(Default)]
pub struct MyStruct {
	pub slice: [u8; 32],
}

But this one doesn’t

#[repr(C)]
#[derive(Default)]
pub struct MyStruct {
	pub slice: [u8; 33],
}
<anon>:3:2: 3:21 error: the trait `core::default::Default` is not implemented for the type `[u8; 33]` [E0277]
<anon>:3 	pub slice: [u8; 33],
         	^~~~~~~~~~~~~~~~~~~

It seems to be some design decision to stop on 32 items regardless of the primitive’s type. I assume that all those default implementations cannot be expressed generically in std.

What can I use as work-around? In my case the struct contains a lot of values and other nested structs and the only problematic field is of type [u8; 256].

Annotating a custom default value for a single field would be great!


#2

You can use a newtype wrapper

struct Buffer([u8; 256]);

impl Default for Buffer {
    fn default() -> Self { Buffer([0; 256]) }
}

#3

Sorry, I forgot to mention that the struct is #[repr(C)] - does the newtype have an impact on the internal representation?


#4

I can’t readily point to the documentation here, but I believe that newtype style structs are a compile time only thing. It might be a good idea to add #[repr(C)] to the Buffer itself though, just for documentatation.


#5

Thanks a lot for your fast and helpful response (again :laughing:)!

This forum is great and helps a lot in not losing hope to master Rust someday!