Skip to main content

Mojo struct

Optional

struct Optional[T: Movable]

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 (Movable): The type of value stored in the Optional.

Implemented traits

AnyType, Boolable, Copyable, Defaultable, DevicePassable, Equatable, Hashable, ImplicitlyCopyable, ImplicitlyDestructible, Iterable, IterableOwned, Iterator, 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 = Optional[T]

The owned iterator type for this optional.

IteratorType

comptime IteratorType[iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]] = Optional[T]

The iterator type for this optional.

Parameters

  • iterable_mut (Bool): Whether the iterable is mutable.
  • iterable_origin (Origin): The origin of the iterable.

Methods

__init__

__init__(out self)

Construct an empty Optional.

Examples:

instance = Optional[String]()
print(instance) # Output: None

@implicit __init__(out self, var value: T)

Construct an Optional containing a value.

Examples:

instance = Optional[String]("Hello")
print(instance) # Output: 'Hello'

Args:

  • value (T): The value to store in the Optional.

@implicit __init__(out self, value: NoneType)

Construct an empty Optional.

Examples:

instance = Optional[String](None)
print(instance) # Output: None

Args:

  • value (NoneType): Must be exactly None.

__init__(out self, *, copy: Self)

Copy-initialize an Optional.

Args:

  • copy (Self): The Optional to copy from.

__bool__

__bool__(self) -> Bool

Return true if the Optional has a value.

Returns:

Bool: True if the Optional has a value and False otherwise.

__getitem__

__getitem__(ref self) -> ref[self_is_mut._value] T

Retrieve a reference to the value inside the Optional.

Returns:

ref: A reference to the value inside the Optional.

Raises:

On empty Optional.

__invert__

__invert__(self) -> Bool

Return False if the Optional has a value.

Returns:

Bool: False if the Optional has a value and True otherwise.

__eq__

__eq__(self, rhs: None) -> Bool

Return True if a value is not present.

Args:

  • rhs (None): The None value to compare to.

Returns:

Bool: True if a value is not present, False otherwise.

__eq__(self, rhs: Self) -> Bool where conforms_to(T, AnyType & ImplicitlyDestructible & 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__

__ne__(self, rhs: None) -> Bool

Return True if a value is present.

Args:

  • rhs (None): The None value to compare to.

Returns:

Bool: False if a value is not present, True otherwise.

__is__

__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__

__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__

__iter__(ref self) -> Self

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:

Self: An iterator over the Optional's value (if present).

__iter__(var self) -> Self

Consume the Optional and return an iterator over its value.

Optionals act as a collection of size 0 or 1.

Returns:

Self: An iterator that owns the Optional's value (if present).

__next__

__next__(mut self) -> Optional[T].Element

Return the contained value of the Optional.

Returns:

Optional: The value contained in the Optional.

Raises:

StopIteration if the iterator has been exhausted.

bounds

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: A tuple containing the length (0 or 1) and an Optional containing the length.

__merge_with__

__merge_with__[other_type: AnyStruct[Bool]](self) -> Bool

Merge with other bools in an expression.

Parameters:

  • other_type (AnyStruct): The type of the bool to merge with.

Returns:

Bool: A Bool after merging with the specified other_type.

write_to

write_to(self, mut writer: T) where conforms_to(T, AnyType & ImplicitlyDestructible & Writable)

Write this Optional to a Writer.

Args:

  • writer (T): The object to write to.

write_repr_to

write_repr_to(self, mut writer: T) where conforms_to(T, AnyType & ImplicitlyDestructible & Writable)

Write this Optional's representation to a Writer.

Args:

  • writer (T): The object to write to.

__hash__

__hash__[H: Hasher](self, mut hasher: H) where conforms_to(T, AnyType & 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 get_type_name() -> String where conforms_to(T, AnyType & Copyable & Movable) if conforms_to(T, AnyType & DevicePassable) else conforms_to(T, AnyType & DevicePassable)

Get the human-readable type name for this Optional type.

Returns:

String: A string representation of the type, e.g. Optional[Int].

value

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: A reference to the contained data of the Optional as a reference.

unsafe_value

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: A reference to the contained data of the Optional as a reference.

take

take(mut self) -> T

Move the value out of the Optional.

Notes: This will abort on empty Optional.

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

unsafe_take(mut self) -> T

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.

or_else

or_else[_T: Movable & ImplicitlyDestructible, //](deinit self: Optional[_T], var default: _T) -> _T

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

Parameters:

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

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): Origin of the contained Pointer.
  • _T (Copyable): Type of the owned result value.

Returns:

Optional: An Optional containing an owned copy of the pointee value.

Was this page helpful?