Skip to content

Rust: an enum member that aliases another (Default = Low, or any repeated value) fails to compile with E0081 "discriminant value assigned more than once" #388

Closed

Description

@matt-edmondson

What's wrong

C#, C, C++, Go, Python (as an alias) and JS all allow two enum members with the same value. Default = Low and All = Read are common C# idioms, and #378 already treats Default = None as valid input.

Since #258, RustGenerator.GenerateEnumDeclaration rewrites a sibling reference as Name::Sibling as i32 and writes it as a discriminant:

string name = enumDecl.Name ?? "UnnamedEnum";
code.WriteLine("#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]");
code.Write($"{SpellVisibilityOf(enumDecl)}enum {name} ");
// A variant is not a value in a discriminant, so one naming another is cast to the
// discriminant's type: Perm::Read as i32, or as isize where no representation is fixed.
string discriminant = enumDecl.UnderlyingType is TypeReference fixedType ? SpellType(fixedType) : "isize";
using Scope body = new(code);
foreach (EnumMember member in enumDecl.Members)
{
code.Write(member.Name ?? "Unnamed");
if (member.Value is not null)
{
code.Write($" = {RenameSiblingMembers(enumDecl, member.Value, sibling => $"{name}::{sibling} as {discriminant}")}");
}

Rust variants must have unique discriminants. An alias is therefore E0081, and so is an implicit successor that lands on an existing value.

Repro

Input: enum Bits : int { A = 0x10, B, C = 1 << 3, D, E = A, F }, built with EnumMember.Value strings.

#[repr(i32)]
pub enum Bits { A = 0x10, B, C = 1 << 3, D, E = Bits::A as i32, F, }

rustc reports two errors:

  • E0081: discriminant value 16 assigned more than once (A/E)
  • E0081: discriminant value 17 assigned more than once (B/F)

The g++, gcc, go build, python3 and node outputs for the same input all build and run.

Suggested fix / acceptance criteria

  • Write a member whose value repeats an earlier member's value as an associated constant instead of a variant:
    impl Bits { #[allow(non_upper_case_globals)] pub const E: Bits = Bits::A; }
  • A value that is exactly a sibling's name is the minimum case. Implicit successors after an alias need the same treatment, so F becomes pub const F: Bits = Bits::B.
  • A Rust compile test covering Level { Low, Mid, High, Default = Low } and the Bits enum above, asserting Bits::E as i32 == 16 and Bits::F as i32 == 17.

Activity

  1. added
    bug
    on Oct 30, 2026
  2. matt-edmondson commented on Oct 30, 2026

    @matt-edmondson
    ContributorAuthor

    Triage


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions