Variant

#import "std/variant"

Variant is a light-weight tagged union helper built on top of a plain union type. It wraps an existing union and augments it with a discriminant kind, so you can safely track which union member is currently active.

A new variant type can be easily created by Variant helper function.

To set variant to a new value use:

To get variant value use:

To check which kind is currenlty set for the variant use:

Example

#import "experimental/variant"
var: Variant(union { my_int: s32; my_float: f32; });

main :: fn () s32 {
    set_variant(&var, .my_float, 10.f);
    switch var.kind {
        .my_int   {
            print("Value is int: %\n", var.my_int);
        }
        .my_float {
            print("Value is float: %\n", var.my_float);
        }
    }

    return 0;
}

Variant

Variant :: fn (TUnion: type) type

Wraps the TUnion type into new Variant type.

Returns a new structure based on passed union with added kind member of implicit enum type generated from top-level union member names. This kind is used to identify which union member is currently set in runtime.

Note that Variant follows the zero-initialization rules of the language, meaning zero initialized variant is set to the first kind by default.

File: variant.bl

is_variant_of

is_variant_of :: fn (variant: *?T, kind: variant_typeof_kind(T)) bool #inline

Returns true in case the variant holds value of kind.

File: variant.bl

get_variant

get_variant :: fn (variant: *?T, kind: variant_typeof_kind(T)) get_struct_member_type(T.base) #inline

Gets variant of kind by value (creates copy).

Panics in case the variant does not hold value of kind.

File: variant.bl

get_variant_ref

get_variant_ref :: fn (variant: *?T, kind: variant_typeof_kind(T)) *get_struct_member_type(T.base) #inline

Gets variant of kind by reference.

Panics in case the variant does not hold value of kind.

File: variant.bl

set_variant

set_variant :: fn (variant: *?T, kind: variant_typeof_kind(T), v: get_struct_member_type(T.base))  #inline

Sets variant to v by value and set variant kind.

File: variant.bl

set_variant_ref

set_variant_ref :: fn (variant: *?T, kind: variant_typeof_kind(T), v: *get_struct_member_type(T.base))  #inline

Sets variant to v by reference (internal copy of v is done) and set variant kind.

File: variant.bl

emplace_variant

emplace_variant :: fn (variant: *?T, kind: variant_typeof_kind(T), noinit :: false) *get_struct_member_type(T.base) #inline

Sets variant kind and return pointer to zero initialized variant data in case noinit is false.

File: variant.bl