Search code examples
enumsjuliasymbols

Converting enums to symbols in Julia


I have a definition of an enum as below. I would like to map each instance of the enum into the corresponding symbol. I can do this by manually constructing an array symbols and indexing into it. Is there a way of accomplishing this without specifying the array of symbols by hand?

@enum MyEnum A=1 B=2 C=3

symbols = [:A, :B, :C]

function enumToSymbol(x::MyEnum) :: Symbol
    return symbols[Int(x)]
end

@assert enumToSymbol(A) == :A

Solution

  • Just use Symbol:

    julia> @enum MyEnum A=1 B=2 C=3
    
    julia> Symbol(A)
    :A
    
    julia> x = A
    A::MyEnum = 1
    
    julia> Symbol(x)
    :A
    

    as it is defined as follows:

    Base.Symbol(x::Enum) = namemap(typeof(x))[Integer(x)]::Symbol
    

    in particular you have an un-exported:

    julia> Base.Enums.namemap(typeof(x))
    Dict{Int32,Symbol} with 3 entries:
      2 => :B
      3 => :C
      1 => :A