External Publication
Visit Post

Could collections hypothetically store keys and values inline?

Rust Internals [Unofficial] April 23, 2026
Source

Speaking only with respect to the default allocator:

Vec<T> and String document that they never use any sort of "small optimization" where some [T] or str data is stored inline in the main Vec or String allocation. They also do not have unique/noalias semantics like Box<T> or &mut T do; although this is technically not documented, because people already rely on this property, it would be considered a breaking change to add noalias semantics to them: https://github.com/rust-lang/rfcs/pull/3712#issuecomment-3715013712

These guarantees (and other guarantees of the language) imply that self-referential structs can soundly use Vec<T>s or Strings as backing data for self-references to the associated [T] or str data; moving a Vec<T> or String does not invalidate references (whether & or &mut) to their heap data.

The data structures in std::collections, however, do not explicitly document that they never store values (or, if applicable, keys) inline; AFAICT, this is technically "just" an undocumented implementation detail of std. Should I start making an RFC requesting this guarantee?

Or is there some reason I'm missing that already prevents std::collections data structures from storing values and (if applicable) keys inline, even hypothetically? In other words, can unsafe code stably and soundly use e.g. a HashMap as backing data for self-references to keys and values?

Discussion in the ATmosphere

Loading comments...