Is allocating a structure in a heap or has a structure that is a pointer to a heap more idiomatic?

I have a type that takes up too much stack space:

struct Foo {
    lots_of_bytes: [u8; 1024 * 10],
    bar: bool,
    baz: isize,
}

There are two obvious solutions:

let foo = Box::new(Foo::new());

Or

struct Foo {
    lots_of_bytes: Box<[u8; 1024 * 10]>,
    bar: bool,
    baz: isize,
}

To summarize, I either select the entire structure on the heap, or I may have my own heap pointer. Is any of these solutions an “idiomatic” solution? Or is it strictly subjective or contextual?

+4
source share
1 answer

I think that the question that you need to ask yourself here will be: does it make sense to place this structure on the stack? If the answer is no, then you should probably ensure allocation on the heap. You have two alternatives for this:

  • Use lots_of_bytes: Box<[u8; 1024 * 10]>.
  • lots_of_bytes: [u8; 1024 * 10] , Foo Box<Foo ( Foo ).

, :

  • Foo , .
  • lots_of_bytes, . , bar baz , .

, - , .

+4

Source: https://habr.com/ru/post/1674620/


All Articles