zig/doc/langref/test_union_method.zig
Gordon Cassie 24f28753e6
Document a few non-obvious variable assignments (#20213)
Provide examples of various initializations.
2024-06-08 12:39:11 -07:00

31 lines
648 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 };
var v3: Variant = .none;
try expect(v1.truthy());
try expect(!v2.truthy());
try expect(!v3.truthy());
}
// test