-
Notifications
You must be signed in to change notification settings - Fork 3
Enum
Chung Leong edited this page Feb 11, 2024
·
8 revisions
Zig enums 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
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"