Niche Optimization

1. #[derive(Debug)]
2. enum List<T> {
3. Cons(T, Box<List<T>>),
4. Nil,
5. }

7. fn main() {
8. let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
9. println!("{list:?}");
10. }

A Box cannot be empty, so the pointer is always valid and non-null. This allows the compiler to optimize the memory layout:

19.5.2. Niche Optimization - 图1