@@ -89,34 +89,32 @@ fn main() {
8989
9090## Niche Optimization
9191
92+ Though ` Box ` looks like ` std::unique_ptr ` in C++, it cannot be empty/null. This
93+ makes ` Box ` one of the types that allow the compiler to optimize storage of some
94+ enums.
95+
96+ For example, ` Option<Box<T>> ` has the same size, as just ` Box<T> ` , because
97+ compiler uses NULL-value to discriminate variants instead of using explicit tag
98+ ([ "Null Pointer Optimization"] ( https://doc.rust-lang.org/std/option/#representation ) ):
99+
92100``` rust,editable
93- #[derive(Debug)]
94- enum List<T> {
95- Element(T, Box<List<T>>),
96- Nil,
97- }
101+ use std::mem::size_of_val;
102+
103+ struct Item(String);
98104
99105fn main() {
100- let list: List<i32> =
101- List::Element(1, Box::new(List::Element(2, Box::new(List::Nil))));
102- println!("{list:?}");
103- }
104- ```
106+ let just_box: Box<Item> = Box::new(Item("Just box".into()));
107+ let optional_box: Option<Box<Item>> =
108+ Some(Box::new(Item("Optional box".into())));
109+ let none: Option<Box<Item>> = None;
105110
106- A ` Box ` cannot be empty, so the pointer is always valid and non- ` null ` . This
107- allows the compiler to optimize the memory layout:
111+ assert_eq!(size_of_val(&just_box), size_of_val(&optional_box));
112+ assert_eq!(size_of_val(&just_box), size_of_val(&none));
108113
109- ``` bob
110- Stack Heap
111- .- - - - - - - - - - - - - - . .- - - - - - - - - - - - - -.
112- : : : :
113- : list : : :
114- : +---------+----+----+ : : +---------+----+----+ :
115- : | Element | 1 | o--+----+-----+--->| Element | 2 | // | :
116- : +---------+----+----+ : : +---------+----+----+ :
117- : : : :
118- : : : :
119- '- - - - - - - - - - - - - - ' '- - - - - - - - - - - - - -'
114+ println!("Size of just_box: {}", size_of_val(&just_box));
115+ println!("Size of optional_box: {}", size_of_val(&optional_box));
116+ println!("Size of none: {}", size_of_val(&none));
117+ }
120118```
121119
122120</details >
0 commit comments