Is using @enum
the only way to declare Julia Enum datatype? If so why?
An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.
In Julia, enumerated types are typically called "enum types". For instance, one could use enum types to describe the seven days of the week, the twelve months of the year, the four suits of a standard 52-card deck, or other similar situations.
Enumerated Type Declaration to Create a Variable Similar to pre-defined data types like int and char, you can also declare a variable for enum and other user-defined data types.
The best way to define the enum is to declare it in header file. So, that you can use it anywhere you want by including that header file during compilation.
It's the only (easy) way, yes. The answer, as often (or, rather, always) in Julia, can be found by looking at the source code. This can be a bit scary at first, but you get used to it after a while!
Normally to create an object of a given type, you call the type's constructor. So you might expect to be able to do
Enum(...)
and create an object of type Enum
.
In this case, however, Enum
is an abstract type, so you cannot do that.
What does @enum
do, then? The example from the manual is
julia> @enum FRUIT apple=1 orange=2 kiwi=3
This actually creates a completely new type, called FRUIT
, that is a subtype of Enum
, and objects of that type called apple
, orange
and kiwi
, which are converted to those numbers by calling Int(apple)
etc. This is done by generating the Julia code to do so, inside the macro.
In principle, you could, yourself, do all the work that the macro does, but the macro is there to make our life easier!
Edit:
Since Julia 0.7, enums can be defined using @enum
macros as you mentionned but can also be used with a begin block:
julia> @enum Fruit begin
apple = 1
orange = 2
kiwi = 3
end
julia> Fruit
Enum Fruit:
apple = 1
orange = 2
kiwi = 3
julia> apple
apple::Fruit = 1
julia> orange
orange::Fruit = 2
julia> kiwi
kiwi::Fruit = 3
julia> Int(orange)
2
julia> string(orange)
"orange"
Enums can also be defined with this begin block without specifying values (in such a case values are starting with 0, not 1)
julia> @enum Fruit begin
apple
orange
kiwi
end
julia> Fruit
Enum Fruit:
apple = 0
orange = 1
kiwi = 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With