Skip to content

Enum size includes sizes of variants that can't be created #69028

Closed
@WaffleLapkin

Description

@WaffleLapkin

I tried this code:

enum MyPhantomData<T> {
    Always,
    Never(T, core::convert::Infallible),
}

#[test]
fn size() {
    assert_eq!(core::mem::size_of::<MyPhantomData<i32>>(), 0); // Err 8 != 0
}

I expected size test to pass because there is only one value of type MyPhantomData<i32> (MyPhantomData::Always). However, it fails because the actual size of MyPhantomData<i32> is 8. It's also notable that MyPhantomData<()> is actually ZST.

This concrete example may seem strange, but this could also appear in generic code like that:

enum MaybeArrayAndT<T> {
    Nothing,
    ArrayAndT(T, [u8; 1024]),
}

fn main() {
    assert_eq!(size_of::<MaybeArrayAndT<Infallible>>(), 0); // Err: 1025 != 0
}

I'm wondering if there are already issues like that? I couldn't find any...

Meta

Rust playground (stable 1.41.0/nightly 2020-02-09 71c7e149e42cb0fc78a8)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-codegenArea: Code generationC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions