Vec<T>

https://news.ycombinator.com/rss Hits: 8
Summary

TL;DRWe explore the internal structure of Rust's Vec<T>, expecting to find simple ptr, len, and capacity fields. Instead, we uncover a series of nested types, each adding a layer of safety and abstraction on top of a raw pointer (*const u8). This deep dive reveals that Vec is built from components like NonNull, RawVec and others (which we explain layer by layer) to form the safe, user-friendly API that we love.As I was reading the Rust API documentation for std::vec::Vec, something interesting caught my eye in the Vec struct definition.pub struct Vec<T, A = Global> where A: Allocator, { } I am looking at you { /* private fields */ } ! "What are you trying to hide from me?" I thought. Was I being sucked into a grand conspiracy? The documentation gives no hints as to what these fields are other than giving us a visual representation of the data structure: ptr len capacity +--------+--------+--------+ | 0x0123 | 2 | 4 | +--------+--------+--------+ | v Heap +--------+--------+--------+--------+ | 'a' | 'b' | uninit | uninit | +--------+--------+--------+--------+ Surely we will find that our Vec has three fields ptr len and capacity. But to be sure we have to go straight to the source. Are you ready to come with me down the rabbit hole and see if we can uncover an age-old mystery?Diving into the struct definition of Vec in std::vec this is what we find:pub struct Vec<T, A: Allocator = Global> { buf: RawVec<T, A>, len: usize, } NOTEWe will be ignoring the Allocator type entirely. This is a topic worth of its own article.Yay, we have len! Okay... that was easy. Now we only need ptr and capacity. We might be home very early, right?No, not really!"What is this misterious RawVec<T, A>?" you rightly ask yourself and where the hell is the ptr and the capacity? Well, let's follow the breadcrumbs!If we type RawVec into the search field of the Rust API documentation we find... nothing!?I knew it! They really are trying to hide something from us!Okay, okay... stay calm, don't str...

First seen: 2025-10-09 11:19

Last seen: 2025-10-09 20:21