For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).
Optional
struct Optional[T: AnyType]
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.
Layout
The layout of Optional is not guaranteed and may change at any time.
The implementation may apply niche optimizations (for example, storing the
None sentinel inside spare bits of T) that alter the resulting layout.
Do not rely on size_of[Optional[T]]() or align_of[Optional[T]]() being
stable across compiler versions. The only guarantee is that the size and
alignment will be at least as large as those of T itself.
If you need to inspect the current size or alignment, use size_of and
align_of, but treat the results as non-stable implementation details.
Examples:
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
Parameters
- T (
AnyType): The type of value stored in theOptional.
Implemented traits
AnyType,
Boolable,
Copyable,
Defaultable,
DevicePassable,
Equatable,
Hashable,
ImplicitlyCopyable,
ImplicitlyDeletable,
Iterable,
IterableOwned,
Movable,
RegisterPassable,
Writable
comptime members
device_type
comptime device_type = Optional[T]
The device-side type for this optional.
Element
comptime Element = T
The element type of this optional.
IteratorOwnedType
comptime IteratorOwnedType where conforms_to(T, ImplicitlyDeletable & Movable) = _OptionalIter[T(ImplicitlyDeletable & Movable)]
The owned iterator type for this optional.
IteratorType
comptime IteratorType[iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]] = _OptionalIter[T(ImplicitlyDeletable & Movable)]
The iterator type for this optional.
Parameters
- iterable_mut (
Bool): Whether the iterable is mutable. - iterable_origin (
Origin[mut=iterable_mut]): The origin of the iterable.
Methods
__init__
def __init__(out self)
Construct an empty Optional.
Examples:
instance = Optional[String]()
print(instance) # Output: None
@implicit
def __init__(out self, var value: T) where conforms_to(T, Movable)
Construct an Optional containing a value.
Examples:
instance = Optional[String]("Hello")
print(instance) # Output: 'Hello'
Args:
- value (
T): The value to store in theOptional.
def __init__[F: def() -> T](out self, *, init_with: F) where (eq F.T, T)
Construct an Optional holding a value produced in place by call.
The value returned by call is constructed directly into the
Optional's storage without being moved, so this is the only way to
populate an Optional whose element type is not Movable. For a
Movable element type, prefer the value constructor.
The init_with keyword is required to disambiguate from the value
constructor: a closure is itself a storable value, so a positional
Optional(f) would store f rather than call it.
Examples:
@fieldwise_init
struct Pinned(Movable where False):
var value: Int
def make() -> Pinned:
return Pinned(7)
var opt = Optional[Pinned](init_with=make)
print(opt.value().value) # Output: 7
Parameters:
- F (
def() -> T): The type of the initializer closure.
Args:
- init_with (
F): A closure returning the value to store. Called exactly once.
@implicit
def __init__(out self, value: NoneType)
Construct an empty Optional.
Examples:
instance = Optional[String](None)
print(instance) # Output: None
Args:
- value (
NoneType): Must be exactlyNone.
__bool__
def __bool__(self) -> Bool
Return true if the Optional has a value.
Returns:
Bool: True if the Optional has a value and False otherwise.
__getitem__
def __getitem__(ref self) -> ref[self_is_mut._value] T
Retrieve a reference to the value inside the Optional.
Returns:
ref[self_is_mut._value] T: A reference to the value inside the Optional.
Raises:
On empty Optional.
__invert__
def __invert__(self) -> Bool
Return False if the Optional has a value.
Returns:
Bool: False if the Optional has a value and True otherwise.
__eq__
def __eq__(self, rhs: None) -> Bool
Return True if a value is not present.
Args:
- rhs (
None): TheNonevalue to compare to.
Returns:
Bool: True if a value is not present, False otherwise.
def __eq__(self, rhs: Self) -> Bool where conforms_to(T, Equatable)
Return True if this is the same as another Optional value, meaning both are absent, or both are present and have the same underlying value.
Args:
- rhs (
Self): The value to compare to.
Returns:
Bool: True if the values are the same.
__ne__
def __ne__(self, rhs: None) -> Bool
Return True if a value is present.
Args:
- rhs (
None): TheNonevalue to compare to.
Returns:
Bool: False if a value is not present, True otherwise.
__is__
def __is__(self, other: NoneType) -> Bool
Return True if the Optional has no value.
Notes:
It allows you to use the following syntax:
if my_optional is None:.
Args:
- other (
NoneType): The value to compare to (None).
Returns:
Bool: True if the Optional has no value and False otherwise.
__isnot__
def __isnot__(self, other: NoneType) -> Bool
Return True if the Optional has a value.
Notes:
It allows you to use the following syntax:
if my_optional is not None:.
Args:
- other (
NoneType): The value to compare to (None).
Returns:
Bool: True if the Optional has a value and False otherwise.
__iter__
def __iter__(ref self) -> _OptionalIter[T(ImplicitlyDeletable & Movable)]
Iterate over the Optional's possibly contained value.
Optionals act as a collection of size 0 or 1.
Examples:
instance = Optional("Hello")
for value in instance:
print(value) # Output: Hello
instance = None
for value in instance:
print(value) # Does not reach line
Returns:
_OptionalIter[T(ImplicitlyDeletable & Movable)]: An iterator over the Optional's value (if present).
def __iter__(var self) -> _OptionalIter[T(ImplicitlyDeletable & Movable)] where conforms_to(T, ImplicitlyDeletable & Movable)
Consume the Optional and return an iterator over its value.
Optionals act as a collection of size 0 or 1.
Returns:
_OptionalIter[T(ImplicitlyDeletable & Movable)]: An iterator that owns the Optional's value (if present).
bounds
def bounds(self) -> Tuple[Int, Optional[Int]]
Return the bounds of the Optional, which is 0 or 1.
Examples:
def bounds():
empty_instance = Optional[Int]()
populated_instance = Optional[Int](50)
# Bounds returns a tuple: (`bounds`, `Optional` version of `bounds`)
# with the length of the `Optional`.
print(empty_instance.bounds()[0]) # 0
print(populated_instance.bounds()[0]) # 1
print(empty_instance.bounds()[1]) # 0
print(populated_instance.bounds()[1]) # 1
Returns:
Tuple[Int, Optional[Int]]: A tuple containing the length (0 or 1) and an Optional containing the length.
write_to
def write_to(self, mut writer: T) where conforms_to(T, Writable)
Write this Optional to a Writer.
Args:
- writer (
T): The object to write to.
write_repr_to
def write_repr_to(self, mut writer: T) where conforms_to(T, Writable)
Write this Optional's representation to a Writer.
Args:
- writer (
T): The object to write to.
__hash__
def __hash__[H: Hasher](self, mut hasher: H) where conforms_to(T, Hashable)
Updates hasher with the hash of the contained value, if present.
A None optional hashes differently from any present value.
Parameters:
- H (
Hasher): The hasher type.
Args:
- hasher (
H): The hasher instance.
get_type_name
static def get_type_name() -> String where conforms_to(T, Copyable) if conforms_to(T, DevicePassable) else conforms_to(T, DevicePassable)
Get the human-readable type name for this Optional type.
Returns:
String: A string representation of the type, e.g. Optional[Int].
value
def value(ref self) -> ref[self_is_mut._value] T
Retrieve a reference to the value of the Optional.
Notes:
This will abort on empty Optional.
Examples:
instance = Optional("Hello")
x = instance.value()
print(x) # Hello
# instance = Optional[String]() # Uncomment both lines to crash
# print(instance.value()) # Attempts to take value from `None`
Returns:
ref[self_is_mut._value] T: A reference to the contained data of the Optional as a reference.
unsafe_value
def unsafe_value(ref self) -> ref[self_is_mut._value] T
Unsafely retrieve a reference to the value of the Optional.
Notes:
This will not abort on empty Optional.
Examples:
instance = Optional("Hello")
x = instance.unsafe_value()
print(x) # Hello
instance = Optional[String](None)
# Best practice:
if instance:
y = instance.unsafe_value() # Will not reach this line
print(y)
# In debug builds, this will deterministically abort:
y = instance.unsafe_value()
print(y)
Returns:
ref[self_is_mut._value] T: A reference to the contained data of the Optional as a reference.
take
def take(mut self) -> T where conforms_to(T, Movable)
Move the value out of the Optional.
Notes:
This will abort on empty Optional. This leaves the Optional
empty rather than consuming it; use into_inner() to consume it.
Examples:
instance = Optional("Hello")
print(instance.bounds()[0]) # Output: 1
x = instance.take() # Moves value from `instance` to `x`
print(x) # Output: Hello
# `instance` is now `Optional(None)`
print(instance.bounds()[0]) # Output: 0
print(instance) # Output: None
# Best practice
if instance:
y = instance.take() # Won't reach this line
print(y)
# Used directly
# y = instance.take() # ABORT: `Optional.take()` called on empty `Optional` (via runtime `abort`)
# print(y) # Does not reach this line
Returns:
T: The contained data of the Optional as an owned T value.
unsafe_take
def unsafe_take(mut self) -> T where conforms_to(T, Movable)
Unsafely move the value out of the Optional.
Notes:
This will not abort on empty Optional.
Examples:
instance = Optional("Hello")
print(instance.bounds()[0]) # Output: 1
x = instance.unsafe_take() # Moves value from `instance` to `x`
print(x) # Output: Hello
# `instance` is now `Optional(None)`
print(instance.bounds()[0]) # Output: 0
print(instance) # Output: None
# Best practice:
if instance:
y = instance.unsafe_take() # Won't reach this line
print(y)
# In debug builds, this will deterministically abort:
y = instance.unsafe_take() # ABORT: `Optional.take()` called on empty `Optional` (via `debug_assert`)
print(y) # Does not reach this line
Returns:
T: The contained data of the Optional as an owned T value.
into_inner
def into_inner(deinit self) -> T where conforms_to(T, Movable)
Consume the Optional and return the value it contains.
Unlike take(), which needs only a mutable reference and leaves the
Optional empty, this consumes the Optional.
Notes:
This will abort on empty Optional.
Examples:
instance = Optional("Hello")
x = instance^.into_inner() # `instance` is consumed
print(x) # Output: Hello
# Best practice
instance2 = Optional[String](None)
if instance2:
y = instance2^.into_inner() # Won't reach this line
print(y)
# Used directly
# y = instance2^.into_inner() # ABORT: `Optional.into_inner()` called on empty `Optional`
# print(y) # Does not reach this line
Returns:
T: The contained data of the Optional as an owned T value.
deinit_with
def deinit_with[F: def(var T) -> None](deinit self, deinit_func: F, /) where (eq F.T, T)
Destroy the value contained in this Optional in-place using a caller-provided deinitializer function.
This method can be used to destroy Optional values whose element
type is not ImplicitlyDeletable. The __deinit__ on Optional
requires T: ImplicitlyDeletable, so explicit-deinit users must
destroy an Optional[T] through this API instead.
If self is empty, deinit_func is not called. Otherwise
deinit_func is called exactly once on the contained value.
Examples:
@fieldwise_init
struct ExplicitDeinit(Movable, ImplicitlyDeletable where False):
var data: Int
def explicit_deinit(deinit self):
pass
var opt = Optional(ExplicitDeinit(5))
opt^.deinit_with(ExplicitDeinit.explicit_deinit)
Parameters:
- F (
def(var T) -> None): The type of the caller-provided deinitializer function.
Args:
- deinit_func (
F): Caller-provided deinitializer function for destroying an instance ofSelf.T. Not called whenselfis empty.
deinit_assert_empty
def deinit_assert_empty(deinit self)
Destroys an empty Optional, asserting that it holds no value.
Use this on an Optional[T] whose element type is not
ImplicitlyDeletable when the value is known to be empty. Unlike
deinit_with, it takes no deinitializer function (there is no live
value to destroy). In safe-assert builds it aborts if the Optional
is non-empty.
Examples:
var opt: Optional[ExplicitDeinit] = None
opt^.deinit_assert_empty()
or_else
def or_else(deinit self, var default: T) -> T where conforms_to(T, ImplicitlyDeletable & Movable)
Return the underlying value contained in the Optional or a default value if the Optional's underlying value is not present.
Examples:
instance = Optional("Hello")
print(instance) # Output: 'Hello'
print(instance.or_else("Bye")) # Output: Hello
instance = None
print(instance) # Output: None
print(instance.or_else("Bye")) # Output: Bye
Args:
- default (
T): The new value to use if no value was present.
Returns:
T: The underlying value contained in the Optional or a default value.
copied
def copied[mut: Bool, origin: Origin[mut=mut], //, _T: Copyable](self: Optional[Pointer[_T, origin]]) -> Optional[_T]
Converts an Optional containing a Pointer to an Optional of an owned value by copying.
Examples:
Copy the value of an Optional[Pointer[_]]
var data = "foo"
var opt = Optional(Pointer(to=data))
var opt_owned: Optional[String] = opt.copied()
Notes:
If self is an empty Optional, the returned Optional will be
empty as well.
Parameters:
- mut (
Bool): Mutability of the pointee origin. - origin (
Origin[mut=mut]): Origin of the containedPointer. - _T (
Copyable): Type of the owned result value.
Returns:
Optional[_T]: An Optional containing an owned copy of the pointee value.
map
def map[To: Movable, //, Mapper: def(var T) -> To](deinit self, mapper: Mapper) -> Optional[To] where conforms_to(T, Movable) where (eq Mapper.T, T) where (eq Mapper.To, To)
Applies a function to the contained value (if any), returning an Optional containing the result.
Transforms Optional[T] into Optional[To] by applying mapper to
the contained value. If self is empty, returns an empty Optional[To]
without calling mapper.
Examples:
Map the value inside an Optional to a different type:
var opt = Optional("hello")
var length = opt.map(String.byte_length)
print(length.value()) # Output: 5
If the Optional is empty, the mapper is not called:
var opt = Optional[String](None)
var length = opt.map(String.byte_length)
print(length.or_else(-1)) # Output: -1
Parameters:
- To (
Movable): The result type of the mapping closure. - Mapper (
def(var T) -> To): The type of the mapping closure.
Args:
- mapper (
Mapper): The closure to apply to the contained value.
Returns:
Optional[To]: An Optional[To] containing the mapped value, or None if self
was empty.
and_then
def and_then[To: Movable, //, Mapper: def(var T) -> Optional[To]](deinit self, mapper: Mapper) -> Optional[To] where conforms_to(T, Movable) where (eq Mapper.T, T) where (eq Mapper.To, To)
Calls mapper on the contained value (if any), returning the result.
Unlike map(), the mapper function itself returns an Optional. This
allows chaining operations that may each independently fail. Sometimes
called "flat map" in other languages.
Examples:
Chain operations that may each return None:
def try_parse_int(s: String) -> Optional[Int]:
try:
return Int(s)
except:
return None
def main():
var opt = Optional("42")
var parsed = opt.and_then(try_parse_int)
print(parsed.value()) # Output: 42
If the Optional is empty, the mapper is not called:
def main():
var opt = Optional[String](None)
var parsed = opt.and_then(try_parse_int)
print(parsed.or_else(-1)) # Output: -1
Parameters:
- To (
Movable): The value type of theOptionalreturned by the mapper. - Mapper (
def(var T) -> Optional[To]): The type of the mapping function.
Args:
- mapper (
Mapper): The function to apply to the contained value. Must return anOptional[To].
Returns:
Optional[To]: The Optional[To] returned by mapper, or None if self was
empty.