Enums and flags
Crow supports enum
and flags
types
mostly for compatibility with C, but you might find them useful in other contexts.
Enum types
An enum type is a type that has only a specified set of possible values.
It's like a union
, except that choices can't have any associated value.
This restriction brings with it easy conversion to/from a number or string.
match
expressions work the same for enums as they do for unions.
Also as with a union, declaring the enum generates functions left
and right
returning enum values.
The similarity makes it easy to change an enum to union (or vice versa) without breaking too much code.
Conversion
An enum can be converted to a symbol
, string
,
or its backing type (usually nat32
).
You can also convert back from a symbol
or string
,
which returns an option of the enum.
Custom storage type
By default, enums are stored as a nat32
,
but you can make it a different size of nat
,
or even an int
.
You can also choose what integer values are associated with each value.
(The default is 0, 1, 2, ... like in C.)
Doing so requires you to use the expanded syntax with one line per enum member.
Flags types
While enum types store one of the choices, flags types store any number of the choices.
Declaring a flags
type declares a function |
that gets the union of flags and &
that gets the intersection.
As with enums, you can specify the backing type and exactly what value each flag has.
Make sure they are powers of 2.