Story Details

  • A surprising enum size optimization in the Rust compiler

    Posted: 2025-04-07 22:30:45

    Rust enums can surprisingly be smaller than expected. While naively, one might assume an enum's size is determined by the largest variant plus a discriminant to track which variant is active, the compiler optimizes this. If an enum's largest variant contains data with internal padding, the discriminant can sometimes be stored within that padding, avoiding an increase in the overall size. This optimization applies even when using #[repr(C)] or #[repr(u8)], so long as the layout allows it. Essentially, the compiler cleverly utilizes existing unused space within variants to store the variant tag, minimizing the enum's memory footprint.

    Summary of Comments ( 1 )
    https://news.ycombinator.com/item?id=43616649

    Hacker News users discussed the surprising optimization where Rust can reduce the size of an enum if its variants all have the same representation. Some commenters expressed admiration for this detail of the Rust compiler and its potential performance benefits. A few questioned the long-term stability of relying on this optimization, wondering if changes to the enum's variants could inadvertently increase its size in the future. Others delved into the specifics of how this optimization interacts with features like repr(C) and niche filling optimizations. One user linked to a relevant section of the Rust Reference, further illuminating the compiler's behavior. The discussion also touched upon the potential downsides, such as making the generated assembly more complex, and how using #[repr(u8)] might offer a more predictable and explicit way to control enum size.