Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Created July 14, 2022 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hnakamur/22015e02786b5d2da2bf3ad04f2f90f8 to your computer and use it in GitHub Desktop.
Save hnakamur/22015e02786b5d2da2bf3ad04f2f90f8 to your computer and use it in GitHub Desktop.
create union enum in Zig
const std = @import("std");
const expect = std.testing.expect;
const Variant = union(enum) {
int: i32,
boolean: bool,
// void can be omitted when inferring enum tag type.
none,
fn truthy(self: Variant) bool {
return switch (self) {
Variant.int => |x_int| x_int != 0,
Variant.boolean => |x_bool| x_bool,
Variant.none => false,
};
}
};
test "union method" {
var v1 = Variant{ .int = 1 };
var v2 = Variant{ .boolean = false };
try expect(v1.truthy());
try expect(!v2.truthy());
}
test "create union" {
const allocator = std.testing.allocator;
var v1 = try allocator.create(Variant);
defer allocator.destroy(v1);
v1.* = .{ .int = 1 };
try expect(v1.truthy());
}
$ zig test create_enum_union.zig
All 2 tests passed.
$ zig version
0.10.0-dev.2880+6f0807f50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment