14159
14159

Reputation: 185

Size of types implementing a trait

I want to define a slice of MaybeUninit of trait objects, something like [MaybeUnint<dyn MyTrait>;2]. Of course, this doesn't work because Rust doesn't know the size of a dyn MyTrait at compile time. So my question is, is there a way to require the types implementing a trait be of a certain size? e.g. so anything that implements MyTrait takes up 4 bytes?

Link to the playground

In response to @AleksanderKrauze's comment: I'm trying to build a "composable" memory memory allocator. I have a struct ChunkAllocator<CHUNK_SIZE> that allocates in fixed-sized chunks, and I want to store a few of them in a slice to create an allocator that can allocate different sizes. So they are all implementing the same trait (Allocator) and have the same size (or at least I can bound it) but the type signature is different. I'd like to keep the allocation size as part of the type rather than move it to a field inside the struct.

Upvotes: 0

Views: 70

Answers (0)

Related Questions