mirror of
https://github.com/google/comprehensive-rust.git
synced 2024-12-17 15:21:32 +02:00
f16b41f012
* Further simplify `Box` diagrams I think we can improve the drawing by simplifying them and making them more symbolic. Followup to #374. * Apply suggestions from code review
1.1 KiB
1.1 KiB
Niche Optimization
#[derive(Debug)]
enum List<T> {
Cons(T, Box<List<T>>),
Nil,
}
fn main() {
let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
println!("{list:?}");
}
A Box
cannot be empty, so the pointer is always valid and non-null
. This
allows the compiler to optimize the memory layout:
Stack Heap
.- - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - - -.
: : : :
: list : : :
: +----+----+ : : +----+----+ +----+------+ :
: | 1 | o--+-----------+-----+--->| 2 | o--+--->| // | null | :
: +----+----+ : : +----+----+ +----+------+ :
: : : :
: : : :
`- - - - - - - - - - - - -' '- - - - - - - - - - - - - - - - - - - - - - -'