BorrowCheck › Rust language core
Memory and type layout
Stack and heap, sizes and alignment, zero-sized types, niches, allocation cost, Sized and DSTs.
The topic explains where values live and how much space they take. The subtopic on the stack and the heap covers why a Vec lives in two places at once, what moving an array and a Box costs, why a large array on the stack is dangerous, and what limits a thread's stack. The questions on sizes and alignment check padding, field reordering in repr(Rust) and what that layout does not guarantee, the alignment of u128, and ways to measure a layout with size_of and align_of. The subtopics on zero-sized types and niches show why HashSet is built as HashMap<K, ()>, how Box and pointers handle ZSTs, why Option<&T> costs nothing while a raw pointer has no niche, and how bool, char and NonZero leave room for a discriminant. The subtopic on allocations examines what actually calls the allocator: empty containers, Vec growth, collect with size_hint, into_boxed_slice, Rc::new and Rc::clone, and string concatenation. The last subtopic is about Sized and dynamically sized types: where a DST cannot live, what ?Sized means, how a struct with an unsized tail is laid out, and what size_of_val returns for a trait object.
43 questions: 19 basic, 20 intermediate, 4 advanced. 6 info pages, 7 sources.
Subtopics
- Stack and heap
- Sizes and alignment
- Zero-sized types
- Niche optimization and enum layout
- Allocations and their cost
Sizedand DSTs
Previous: Testing, benchmarks, profiling · Next: Tooling