Created
July 14, 2022 03:37
-
-
Save hnakamur/22015e02786b5d2da2bf3ad04f2f90f8 to your computer and use it in GitHub Desktop.
create union enum in Zig
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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