3 ms·
This may be a stupid question, but will the array of const generic structures stack allocated or dynamicly? Or are there both versions?
by xiphias2 6y ago
This may be a stupid question, but will the array of const generic structures stack allocated or dynamicly? Or are there both versions?
- est31 6y agoThe size of the arrays will still be determined at compile time to a specific value. This only allows code to be written that is generic in terms of the size of the array, but it still requires some other place of the codebase to supply an actual size for it to become part of the executable.
- rkangel 6y agoAs with any other rust value it depends how you create it. If you just to "let x = ..." in your function then it'll be on the stack. If you do "let x = Box<...>" then it'll be on the heap.
- GolDDranks 6y agoIt's not a stupid question! The short answer is: the compiler doesn't care. An array of type [T; N] (where T is the type of the elements and N is the length of the array) can be allocated on the stack or in the heap (using Box<T>, as stated in sibling comments). If you access it by value, it will be copied as-is, so be careful with large arrays! You mostly access them behind a reference, but in that case, the type of the reference will be &'a [T; N] where 'a is the lifetime of the referent value. The type system by itself doesn't actually care whether the value lives in heap or stack.
- brundolf 6y agoTo refine what another comment has said: the array will be local (not across a pointer) to whatever struct or block it's contained in. So if it's contained in a heap-allocated struct (a Box or a Vec for example), it will be on the heap (within that struct, not behind another pointer). If it isn't contained within a heap-allocated struct, it will be on the stack (or if it's a const, it'll be in a static location). This is why arrays in Rust must always have a statically-known size: because they themselves do not create heap-allocations, so the compiler must know how much space to set aside for them. And that fact is why const generics are such a big deal: they allow a certain kind of variability in that static size for different invocations of the same piece of code, so long as the size can still be determined for each usage at compile time.