Enum - chung-leong/zigar GitHub Wiki
In the Zig language, an enum is a set of named integers. They are represented as unique objects in JavaScript.
const std = @import("std");
pub const Pet = enum { dog, cat, dragon };
pub fn print(pet: Pet) void {
std.debug.print("pet = {s}\n", .{@tagName(pet)});
}
import { Pet, print } from './enum-example-1.zig';
console.log(typeof Pet.dog);
print(Pet.dog);
print(Pet.cat);
object
dog
cat
Type conversion
string
and number
are casted automatically to enums with the corresponding name or value.
import { print } from './enum-example-1.zig';
print('dog');
print(1);
try {
print('dingo');
} catch (err) {
console.log(err.message);
}
pet = dog
pet = cat
print(args[0]): Enum item of the type enum-example-1.Pet expected, received dingo
Conversely, enums can be converted to string
and number
using String() and Number().
import { Pet } from './enum-example-1.zig';
console.log(String(Pet.cat));
console.log(Number(Pet.cat));
cat
1
valueOf() and JSON.stringify() also convert enums to strings.
import { Pet } from './enum-example-1.zig';
console.log(Pet.cat.valueOf());
console.log(JSON.stringify(Pet.cat));
cat
"cat"
Non-exhaustive enum
When an enum type is declared to be non-exhaustive, an anonymous enum object would be created every time you employ a number that hasn't been seen before.
const std = @import("std");
pub const JunkFood = enum(u16) {
hamburger,
hotdog,
donut,
pizza,
taco,
_,
};
pub var junk: JunkFood = .donut;
pub fn print() void {
std.debug.print("junk = {any}\n", .{junk});
}
import { JunkFood, default as module, print } from './enum-example-2.zig';
console.log(`donut? ${module.junk === JunkFood.donut}`);
module.junk = JunkFood.taco;
console.log(`taco? ${module.junk === JunkFood.taco}`);
print();
module.junk = 101;
console.log(`mystery food #100? ${module.junk === JunkFood(100)}`);
console.log(`mystery food #101? ${module.junk === JunkFood(101)}`);
print();
donut? true
taco? true
junk = enum-example-2.JunkFood.taco
mystery food #100? false
mystery food #101? true
junk = enum-example-2.JunkFood(101)
In packed struct
Enums can appear inside packed structs when they're declared with explicit
integer types (new requirement in Zig 0.12.0). An enum with 4 items would need an u2
, while an
enum with 8 items would need u3
.
pub const Pet = enum(u2) { dog, cat, dragon, kangaroo };
pub const Car = enum(u3) { Toyota, Ford, Volkswagen, Tesla, Saab, Fiat, Nissan, Kia };
pub const Computer = enum(u2) { Apple, Dell, Lenovo, HP };
pub const Owner = packed struct {
pet: Pet,
car: Car,
computer: Computer,
};
import { Owner } from './enum-example-3.zig';
const owner = new Owner({ pet: 'kangaroo', car: 'Toyota', computer: 'Dell' });
console.log(owner.valueOf());
console.log(`size = ${owner.dataView.byteLength}`);
{ pet: 'kangaroo', car: 'Toyota', computer: 'Dell' }
size = 1