Skip to content

Convert enum to struct assist #21612

@ds84182

Description

@ds84182

This is useful for hiding enum variants from a public API.

e.g.

#[derive(Copy, Clone, Debug)]
pub enum Something {
  Foo,
  Bar(u32),
}

fn foo(s: &Something) -> u32 {
  match s {
    Something::Foo => 0,
    Something::Bar(value) => value,
  }
}

fn bar() -> Something {
  Something::Foo
}

to

#[derive(Copy, Clone, Debug)]
#[repr(transparent)] // In case of transmute shenanigans
pub struct Something {
  kind: SomethingKind,
}

// Duplicates basic derives (can't duplicate all because it may change semantics, e.g. serde)
#[derive(Copy, Clone, Debug)]
enum SomethingKind {
  Foo,
  Bar(u32),
}

fn foo(s: &Something) -> u32 {
  match &s.kind {
    Something::Foo => 0,
    Something::Bar(value) => value,
  }
}

fn bar() -> Something {
  Something { kind: SomethingKind::Foo }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions