authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-04-08 18:03:02-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-04-08 18:03:09-04:00
log292d0cbdadd453874af6e2065638a88d4dda8a10
treeb4f90b289df6228d861b12e601f7bed09a601ef2
parenteae355d77168d655273afa298dc921c40a36bd0b

add docs for union methods


1 files changed, 21 insertions(+), 1 deletions(-)

doc/langref.html.in+21-1
...@@ -2033,7 +2033,27 @@ test "union variant switch" {...@@ -2033,7 +2033,27 @@ test "union variant switch" {
2033 assert(mem.eql(u8, what_is_it, "this is a number"));2033 assert(mem.eql(u8, what_is_it, "this is a number"));
2034}2034}
20352035
2036// TODO union methods2036// Unions can have methods just like structs and enums:
2037
2038const Variant = union(enum) {
2039 Int: i32,
2040 Bool: bool,
2041
2042 fn truthy(self: &const Variant) bool {
2043 return switch (*self) {
2044 Variant.Int => |x_int| x_int != 0,
2045 Variant.Bool => |x_bool| x_bool,
2046 };
2047 }
2048};
2049
2050test "union method" {
2051 var v1 = Variant { .Int = 1 };
2052 var v2 = Variant { .Bool = false };
2053
2054 assert(v1.truthy());
2055 assert(!v2.truthy());
2056}
20372057
20382058
2039const Small = union {2059const Small = union {