Skip to main content

Mojo module

optional

Defines Optional, a type modeling a value which may or may not be present.

Optional values can be thought of as a type-safe nullable pattern. Your value can take on a value or None, and you need to check and explicitly extract the value to get it out.

from collections import Optional
var a = Optional(1)
var b = Optional[Int](None)
if a:
print(a.value()) # prints 1
if b: # bool(b) is False, so no print
print(b.value())
var c = a.or_else(2)
var d = b.or_else(2)
print(c) # prints 1
print(d) # prints 2
from collections import Optional
var a = Optional(1)
var b = Optional[Int](None)
if a:
print(a.value()) # prints 1
if b: # bool(b) is False, so no print
print(b.value())
var c = a.or_else(2)
var d = b.or_else(2)
print(c) # prints 1
print(d) # prints 2

Structs