Bob: i still don't get what Box in Rust is
Tony: @Bob it's heap allocated
Tucker: @Bob if you don't use box, generally it is allocated on the stack, rust controls this very carefully. It wants to know the size of everything on there(the stack) at all times. However, the heap is less controlled, it's a larger, less organized, and "somewhat slower" bit of memory. It cares less the exact size of what is there. So, when you box something, you are allocation heap space for that item, and putting a pointer to that item in the stack. Pointers are known size, though what they point to may not be.
^ probably not "perfectly accurate" explanation, but gives you an idea
Some things in rust will automatically put themselves into the heap over the stack, like Vec so Box<Vec> is not really needed, as Vec is already a pointer to heap space.
Patrick: Another important point is that a box owns the data alocated this way. So when the box is droped, it deallocated the data
Bob: why would i want something to be on the heap when it could be on the stack? From what I've seen the stack is faster
for instance why would i box a bunch of u64
Tucker: you may not, but if you have an array of them that you need to pass around and you only know the size at runtime, then you might have to, as it cannot allocate the stack space at compile time
Patrick: There are 3 main usecases
- Recursive types
- !Sized types like str and [T]
- dynamic lookup
Karen: you usually only have a few megabytes on the stack too
Jake: And resizeable arrays like Vec are something usually done on the heap. So that's one situation where you have a bunch of u64 that are heap allocated.
Since you need the extra flexibility offered by the ability to reallocate
Tucker: also note, the compiler in rust hand holds you though a lot of this, if you enable clippy too, you will follow best practices just by doing what you are told
but the end result is code that is "safe" and memory that is managed