zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 292d0cbdadd453874af6e2065638a88d4dda8a10 (tree)
parent eae355d77168d655273afa298dc921c40a36bd0b
Author: Andrew Kelley <superjoe30@gmail.com>
Date:   Sun,  8 Apr 2018 18:03:02 -0400

add docs for union methods

Diffstat:
Mdoc/langref.html.in | 22+++++++++++++++++++++-
1 file changed, 21 insertions(+), 1 deletion(-)

diff --git a/doc/langref.html.in b/doc/langref.html.in @@ -2033,7 +2033,27 @@ test "union variant switch" { assert(mem.eql(u8, what_is_it, "this is a number")); } -// TODO union methods +// Unions can have methods just like structs and enums: + +const Variant = union(enum) { + Int: i32, + Bool: bool, + + fn truthy(self: &const Variant) bool { + return switch (*self) { + Variant.Int => |x_int| x_int != 0, + Variant.Bool => |x_bool| x_bool, + }; + } +}; + +test "union method" { + var v1 = Variant { .Int = 1 }; + var v2 = Variant { .Bool = false }; + + assert(v1.truthy()); + assert(!v2.truthy()); +} const Small = union {