-
Notifications
You must be signed in to change notification settings - Fork 3
Enum literal
Chung Leong edited this page Apr 17, 2024
·
6 revisions
Enum literals are comptime tokens that you typically cast into enums. They can also be explicitly exported. In JavaScript they are represented as string
.
const Pet = enum{ dog, cat, dragon };
pub const value: Pet = .dragon;
pub const literal = .dragon;
import { value, literal } from './enum-literal-example-1.zig';
console.log(value);
console.log(literal);
enum-literal-example-1.Pet {
[Symbol(memory)]: DataView {
byteLength: 1,
byteOffset: 0,
buffer: ArrayBuffer { [Uint8Contents]: <02>, byteLength: 1 }
}
}
dragon
Because enum literals are automatically converted to string by Zigar, whereas constants of the type []const u8
are treated as arrays, they can be useful in situations where you want to attach a static text to a struct.
pub const DataSection = struct {
comptime type: @TypeOf(.enum_literal) = .data,
offset: i64,
len: i64,
};
import { DataSection } from './enum-literal-example-2.zig';
const section = new DataSection({ offset: 16n, len: 256n });
console.log(section.valueOf());
{ type: 'data', offset: 16n, len: 256n }
You can use the @"" syntax to create literals containing whitespace and other "illegal characters".
pub const version = .@"11.2.2";
import { version } from './enum-literal-example-3.zig';
console.log(version);
11.2.2