Enums are a data type that defines a set of named integer constants.
In V, enums are declared using the
By default, V uses
int to store enum values.
To use any other numeric type (e.g.
u8), you can specify it after the enum
name with the
To get the ordinal of an enum field, use a cast:
To get the string representation of an enum field, use
Sequence numbers start at 0 and increase by 1 for each next enum field.
For each field, you can specify your own value:
If you do not specify a value for the first field, then it will be 0. If you do not specify a value for the next field, then it will be equal to the value of the previous field plus 1.
The compiler can infer which enum the value belongs to:
Enum fields can re-use reserved keywords escaped with an @:
For convenient work with enums, you can use the
Enum match must be exhaustive or have an
This ensures that if a new enum field is added, it's handled everywhere in the code.
Enums can have methods, just like structs.
Enums can be used as bitfields.
To do this, add the
flag attribute to the definition:
The maximum number of fields in such an enum depends on the type you use to store the field values.
For example, if you use
u8, then the maximum number of fields will be 8.
The default is
int so the maximum number of fields will be 32.
In such an enumeration, the fields will have the following values:
You may notice that the values of the enum fields are doubled. In binary, this means that each subsequent enumeration field will have a 1 in binary representation shifted one bit to the left.
Such an enumeration can be used to store multiple values packed into a single number stored in a single variable.
Such enums provide convenient methods for setting/removing bits:
has()– checks if a bit is set
set()– sets a bit
clear()– clears a bit
toggle()– toggles a bit
all()– checks if all bits are set