I'm currently struggling to find the solution of a problem: how to create a generic structure that doesn't take any generic parameters, lifetime annotation or uses heap allocation?
The de-facto way to create a generic structure is to write:
struct Type<T: Trait> {
field: T
}
If we want to get rid of the generic, we can instead use a dynamic reference:
struct Type<'a> {
field: &'a dyn Trait
}
Which works because the reference also contains the length of the type we use under the hood.
If we want to get rid of the lifetime to avoid all generics in the struct, we can allocate the object on the heap:
struct Type {
field: Box<dyn Trait>
}
But this is often not ideal because it requires heap allocation which results in costly memory accesses, and often even creating a value implementing Trait
and then moving it to the heap.
So my question is: is it possible to store a dyn Trait
in a struct without heap allocation nor any generic/lifetime annotation? Something that would store the value itself as well as its length, like Box<dyn Trait>
does but on the stack, or like &'a dyn Trait
does but without using a reference.
Thanks in advance for your help !