Rust enum sizes



I am a little confused about enums. It is my understanding that the enum with have the size equal to max size required for all parameters plus a little extra.

If I have an enum like

pub enum ElementStreamFormat {
  TimeFloatMessage(DateTime<UTC>, f64),

What would be the size here ? Is String the size of the pointer to the heap data ?

I was concerned as I pass a great deal of these through channels and I wanted to add a Vector of Strings to the enum and was wondering how that would effect performance ?



You can ask sizes to rustc:

fn main() {
    use std::mem::size_of;
    println!("{}", size_of::<String>());


The size of a String is basically 3 words: pointer to heap storage, len, and capacity.

A Vecs size is the same (in fact, a String consists of a Vec<u8> internally). The String values inside the Vec are on the heap, so don’t count towards the Vec’s size.

If you were to ever have a very large type, you can put it inside a Box to keep the enum size smaller.

And as @leonardo mentioned, you can ask the compiler to give you the size of any type.


It’s useful to have images of the std lib data structures in the Rust documentation:


Yeah, I’ve seen that cheat sheet and wholeheartedly agree that something like that ought to be in the docs, sort of similar in spirit to the “Choosing your Guarantees” section of the Book.