Skip to content

Syntax extension for converting enums to/from integers #3868

Closed

Description

@erickt

Converting an enum to and from an integer is repetitive and brittle. So instead we should add the traits ToInt/FromInt/ToUint/FromUint, and add a syntax extension to automatically generate implementations of those traits for a given enum.

Activity

  1. nikomatsakis commented on Oct 26, 2012

    @nikomatsakis
    Contributor

    +1

  2. ghost assigned on Oct 26, 2012
  3. graydon commented on Oct 27, 2012

    @graydon
    Contributor

    The 'to' side is currently automatic, foo as uint. The 'from' side is trickier since it has to only consider the valid constructors. In any case, while this is a real problem I do not feel it's best approached via syntax extension. More like an additional dimension of the deriving thing.

  4. sanxiyn commented on Feb 12, 2013

    @sanxiyn
    Contributor

    This is #2132?

  5. erickt commented on Feb 12, 2013

    @erickt
    ContributorAuthor

    That only captures the ToInt side of things. Trying to convert an integer into an enum can be prone to error because you need to make sure the definition of an enum is sharing the same integer bindings as the conversion code. It's easy to add a new variant and forget to update the converters.

  6. erickt commented on Feb 12, 2013

    @erickt
    ContributorAuthor

    Ack, I completely misread #2132. Yes you are right, they are the same. This deriving method @graydon mentioned is the modern way of generating this kind of code.

  7. graydon commented on May 1, 2013

    @graydon
    Contributor

    I suppose I did not know when I wrote that comment that deriving is implemented as a syntax extension. In that case, yeah, let's merge #2132 with this and say this is just a new deriving mode. Nominating for feature complete.

  8. graydon commented on May 9, 2013

    @graydon
    Contributor

    accepted for feature-complete milestone

  9. emberian commented on Jul 7, 2013

    @emberian
    Contributor

    Related to #7080

  10. catamorphism commented on Aug 26, 2013

    @catamorphism
    Contributor

    Bug triage. Milestone looks good to me.

  11. removed their assignment
    on Jun 16, 2014
  12. added a commit that references this issue on Jan 30, 2021
  13. added a commit that references this issue on Aug 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-frontendArea: Compiler frontend (errors, parsing and HIR)A-syntaxextArea: Syntax extensions

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions