Skip to content

Enum literal

Chung Leong edited this page Apr 24, 2024 · 6 revisions

An enum literal is a comptime token that you would typically cast into an enums. It can also be explicitly exported. It's represented as string in JavaScript.

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 strings by Zigar, whereas constants of the type []const u8 are treated as arrays, they can be useful in situations where you want to attach 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

Comptime fields

Clone this wiki locally