Mojo module
variant
Defines a Variant type.
You can use this type to implement variant/sum types. For example:
from utils import Variant
alias IntOrString = Variant[Int, String]
fn to_string(mut x: IntOrString) -> String:
if x.isa[String]():
return x[String]
# x.isa[Int]()
return str(x[Int])
# They have to be mutable for now, and implement CollectionElement
var an_int = IntOrString(4)
var a_string = IntOrString(String("I'm a string!"))
var who_knows = IntOrString(0)
import random
if random.random_ui64(0, 1):
who_knows.set[String]("I'm actually a string too!")
print(to_string(an_int))
print(to_string(a_string))
print(to_string(who_knows))
from utils import Variant
alias IntOrString = Variant[Int, String]
fn to_string(mut x: IntOrString) -> String:
if x.isa[String]():
return x[String]
# x.isa[Int]()
return str(x[Int])
# They have to be mutable for now, and implement CollectionElement
var an_int = IntOrString(4)
var a_string = IntOrString(String("I'm a string!"))
var who_knows = IntOrString(0)
import random
if random.random_ui64(0, 1):
who_knows.set[String]("I'm actually a string too!")
print(to_string(an_int))
print(to_string(a_string))
print(to_string(who_knows))
Structs
-
Variant
: A runtime-variant type.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!