-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_union.zig
96 lines (78 loc) · 1.88 KB
/
test_union.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// tagged union
// union with enum tag
// use switch with a union
const std = @import("std");
const expect = std.testing.expect;
const ComplexTypeTag = enum {
ok,
not_ok,
};
const ComplexType = union(ComplexTypeTag) {
ok: u8,
not_ok: void,
};
test "switch on tagged union" {
const c = ComplexType{ .ok = 42 };
try expect(@as(ComplexTypeTag, c) == ComplexTypeTag.ok);
switch (c) {
ComplexTypeTag.ok => |value| try expect(value == 42),
ComplexTypeTag.not_ok => unreachable,
}
}
test "get tag type" {
try expect(std.meta.Tag(ComplexType) == ComplexTypeTag);
}
test "modify tagged union in switch" {
var d = ComplexType{ .ok = 42 };
switch (d) {
ComplexTypeTag.ok => |*value| value.* += 1,
ComplexTypeTag.not_ok => unreachable,
}
try expect(d.ok == 43);
}
// union method
const Variant = union(enum) {
int: i32,
boolean: bool,
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());
}
// @tagName
const Small2 = union(enum) {
a: i32,
b: bool,
c: u8,
};
test "@tagName" {
try expect(std.mem.eql(u8, @tagName(Small2.a), "a"));
}
// extern union
// memory layout guaranteed to be compatible with the target C ABI.
// packed union
// has well-defined in-memory layout
// anonymous union literals
const Number = union {
int: i32,
float: f64,
};
test "anonymous union literal syntax" {
var i: Number = .{ .int = 42 };
var f = makeNumber();
try expect(i.int == 42);
try expect(f.float == 12.34);
}
fn makeNumber() Number {
return .{ .float = 12.34 };
}