Structs
struct Variant[*Ts: AstNodeLike]
Aliases
alias __del__is_trivial
alias __moveinit__is_trivial
alias __copyinit__is_trivial
Functions
fn __init__(out self, *, unsafe_uninitialized: Tuple[])
fn __init__[T: Movable](out self, var value: T)
fn __copyinit__(out self, other: Self)
fn __moveinit__(out self, var other: Self)
fn __del__(var self)
fn __getitem__[T: AnyType](ref self) -> ref [self] T
This explicitly check that your value is of that type! If you haven’t verified the type correctness at runtime, the program will abort!
For now this has the limitations that it - requires the variant value to be mutable
fn copy(self, out copy: Self)
fn take[T: Movable](mut self) -> T
The caller takes ownership of the underlying value.
This explicitly check that your value is of that type! If you haven’t verified the type correctness at runtime, the program will abort!
fn unsafe_take[T: Movable](mut self) -> T
The caller takes ownership of the underlying value.
This doesn’t explicitly check that your value is of that type! If you haven’t verified the type correctness at runtime, you’ll get a type that looks like your type, but has potentially unsafe and garbage member data.
fn replace[Tin: Movable, Tout: Movable](mut self, var value: Tin) -> Tout
The caller takes ownership of the underlying value.
This explicitly check that your value is of that type! If you haven’t verified the type correctness at runtime, the program will abort!
fn unsafe_replace[Tin: Movable, Tout: Movable](mut self, var value: Tin) -> Tout
The caller takes ownership of the underlying value.
This doesn’t explicitly check that your value is of that type! If you haven’t verified the type correctness at runtime, you’ll get a type that looks like your type, but has potentially unsafe and garbage member data.
fn set[T: Movable](mut self, var value: T)
This will call the destructor on the old value, and update the variant’s internal type and data to the new value.
fn isa[T: AnyType](self) -> Bool
fn unsafe_get[T: AnyType](ref self) -> ref [self] T
This doesn’t explicitly check that your value is of that type! If you haven’t verified the type correctness at runtime, you’ll get a type that looks like your type, but has potentially unsafe and garbage member data.
For now this has the limitations that it - requires the variant value to be mutable
fn is_type_supported[T: AnyType]() -> Bool
Example:
from utils import Variant
def takes_variant(mut arg: Variant):
if arg.is_type_supported[Float64]():
arg = Float64(1.5)
def main():
var x = Variant[Int, Float64](1)
takes_variant(x)
if x.isa[Float64]():
print(x[Float64]) # 1.5
For example, the Variant[Int, Bool]
permits Int
and Bool
.
fn is_in[*V: Copyable & Movable](self) -> Bool
Example:
from utils import Variant
def main():
var x = Variant[Int, Float64](1)
alias OnlyFloats = Variant[Float64, Float32]
# Note the unpacked *VariantName.Ts syntax. This is required to
# see if x also belongs to OnlyFloats.
print(x.is_in[*OnlyFloats.Ts]())