Box, stack and heap

All values in Rust are stack allocated by default. Values can be boxed
(allocated in the heap) by creating a Box<T>. A box is a smart pointer to a
heap allocated value of type T. When a box goes out of scope, its destructor
is called, the inner object is destroyed, and the memory in the heap is freed.

Boxed values can be dereferenced using the * operator; this removes one layer
of indirection.

  1. use std::mem;
  2. #[allow(dead_code)]
  3. #[derive(Debug, Clone, Copy)]
  4. struct Point {
  5. x: f64,
  6. y: f64,
  7. }
  8. #[allow(dead_code)]
  9. struct Rectangle {
  10. p1: Point,
  11. p2: Point,
  12. }
  13. fn origin() -> Point {
  14. Point { x: 0.0, y: 0.0 }
  15. }
  16. fn boxed_origin() -> Box<Point> {
  17. // Allocate this point in the heap, and return a pointer to it
  18. Box::new(Point { x: 0.0, y: 0.0 })
  19. }
  20. fn main() {
  21. // (all the type annotations are superfluous)
  22. // Stack allocated variables
  23. let point: Point = origin();
  24. let rectangle: Rectangle = Rectangle {
  25. p1: origin(),
  26. p2: Point { x: 3.0, y: 4.0 }
  27. };
  28. // Heap allocated rectangle
  29. let boxed_rectangle: Box<Rectangle> = Box::new(Rectangle {
  30. p1: origin(),
  31. p2: origin()
  32. });
  33. // The output of functions can be boxed
  34. let boxed_point: Box<Point> = Box::new(origin());
  35. // Double indirection
  36. let box_in_a_box: Box<Box<Point>> = Box::new(boxed_origin());
  37. println!("Point occupies {} bytes in the stack",
  38. mem::size_of_val(&point));
  39. println!("Rectangle occupies {} bytes in the stack",
  40. mem::size_of_val(&rectangle));
  41. // box size = pointer size
  42. println!("Boxed point occupies {} bytes in the stack",
  43. mem::size_of_val(&boxed_point));
  44. println!("Boxed rectangle occupies {} bytes in the stack",
  45. mem::size_of_val(&boxed_rectangle));
  46. println!("Boxed box occupies {} bytes in the stack",
  47. mem::size_of_val(&box_in_a_box));
  48. // Copy the data contained in `boxed_point` into `unboxed_point`
  49. let unboxed_point: Point = *boxed_point;
  50. println!("Unboxed point occupies {} bytes in the stack",
  51. mem::size_of_val(&unboxed_point));
  52. }