Skip to content

Instantly share code, notes, and snippets.

@mattn
Forked from hnakamur/create_union_enum.zig
Last active July 14, 2022 04:11
Show Gist options
  • Save mattn/151703bb7f31ab823080b49e36c3d6bc to your computer and use it in GitHub Desktop.
Save mattn/151703bb7f31ab823080b49e36c3d6bc to your computer and use it in GitHub Desktop.
create union enum in Zig
const std = @import("std");
const expect = std.testing.expect;
const cell = struct {
v1: ?*Variant,
v2: ?*Variant,
};
const Variant = union(enum) {
int: i32,
boolean: bool,
cell: cell,
// 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.cell => false,
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());
}
test "create union" {
const allocator = std.testing.allocator;
var top = try allocator.create(Variant);
defer allocator.destroy(top);
top.* = .{ .cell = cell{ .v1 = null, .v2 = null } };
var v1 = top;
var i: i32 = 0;
while (i < 3) : (i += 1) {
v1.cell.v1 = try allocator.create(Variant);
v1.cell.v1.?.* = .{ .int = i + 1 };
var v2 = try allocator.create(Variant);
defer allocator.destroy(v2);
v2.* = .{ .cell = cell{ .v1 = null, .v2 = null } };
v1.cell.v2 = v2;
v1 = v2;
}
std.log.warn("{}", .{top.cell.v2.?.cell.v1}); //
}
$ 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