| ... | ... | @@ -2033,7 +2033,27 @@ test "union variant switch" { |
| 2033 | 2033 | assert(mem.eql(u8, what_is_it, "this is a number")); |
| 2034 | 2034 | } |
| 2035 | 2035 | |
| 2036 | | // TODO union methods |
| 2036 | // Unions can have methods just like structs and enums: |
| 2037 | |
| 2038 | const 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 | |
| 2050 | test "union method" { |
| 2051 | var v1 = Variant { .Int = 1 }; |
| 2052 | var v2 = Variant { .Bool = false }; |
| 2053 | |
| 2054 | assert(v1.truthy()); |
| 2055 | assert(!v2.truthy()); |
| 2056 | } |
| 2037 | 2057 | |
| 2038 | 2058 | |
| 2039 | 2059 | const Small = union { |