Skip to content

Layout of single-variant enums #79

Open
@nikomatsakis

Description

@nikomatsakis

Enums that contain a single variant and which do not have an
explicit #[repr] annotation are an important special case. Since
there is only a single variant, the enum must be instantiated with
that variant, which means that the enum is in fact equivalent to a
struct. The question then is to what extent we should guarantee
that the two share an equivalent layout, and also how to define the
interaction with uninhabited types.

As presently implemented, the compiler will use the same layout for
structs and for single variant enums (as long as they do not have a
#[repr] annotation that overrides that choice). So, for example, the
struct SomeStruct and the enum SomeEnum would have an equivalent
layout (playground)::

struct SomeStruct;
enum SomeEnum {
  SomeVariant,
}

Similarly, the struct SomeStruct and the enum SomeVariant in this
example would also be equivalent in their layout
(playground):

struct SomeStruct { x: u32 }
enum SomeEnum {
  SomeVariant { x: u32 },
}

In fact, the compiler will use this optimized layout even for enums
that define multiple variants, as long as all but one of the variants
is uninhabited
(playground):

struct SomeStruct { x: u32 }
enum SomeEnum {
  SomeVariant { x: u32 },
  UninhabitedVariant { y: Void },
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-layoutTopic: Related to data structure layout (`#[repr]`)C-open-questionCategory: An open question that we should revisitS-not-opsemDespite being in this repo, this is not primarily a T-opsem questionT-lang

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions