notes

Log | Files | Refs | README

box.md (1235B)


      1 # Box
      2 
      3 All values in Rust are stack allocated by default. Box is basically a pointer to
      4 a heap allocated value. When Box<T> goes out of scope, its destructor is called,
      5 freeing up the memory on the heap.
      6 
      7 ### Question: when / why to do box in rust?
      8 
      9 We use Box whenever we need to put something on the heap and have a pointer to
     10 it. Because by default Rust values live on the stack, and their size must be
     11 known at compile time.
     12 
     13 ## Use Box<T> when:
     14 
     15 - Recursive types - without Box the type woul dhave inifnite size:
     16 
     17 ```rust
     18 enum List { Cons(i32, Box<List>), Nil }
     19 ```
     20 
     21 - Types whose size can’t be known at compile time but you need a sized handle:
     22 
     23 Trait objects like `Box<dyn Error>` or `Box<dyn MyTrait>` put the unknown‑sized
     24 value on the heap and give you a pointer of known size so functions can return
     25 or store them easily.
     26 
     27 - Moving large data efficiently:
     28 
     29 If you have a big struct and want to move ownership around without copying all
     30 its bytes on the stack, you can store it in a Box and move just the pointer
     31 (cheap copy).
     32 
     33 ## Don't need Box
     34 
     35 For example, Vec<T>, String, HashMap<K, V>, etc., these already have a pointer,
     36 so dont need Box for them.
     37 
     38 [Reference](https://rustwiki.org/en/rust-by-example/std/box.html)