Niche Optimization

  1. #[derive(Debug)]
  2. enum List<T> {
  3. Cons(T, Box<List<T>>),
  4. Nil,
  5. }
  6. fn main() {
  7. let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
  8. println!("{list:?}");
  9. }

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