mirror of
https://codeberg.org/ziglang/zig.git
synced 2025-12-06 13:54:21 +00:00
28 lines
583 B
Zig
28 lines
583 B
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
|