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 theOptional.
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
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 theOptional.
@implicit
__init__(out self, value: NoneType)
Construct an empty Optional.
Examples:
instance = Optional[String](None)
print(instance) # Output: None
Args:
- value (
NoneType): Must be exactlyNone.
__init__(out self, *, copy: Self)
Copy-initialize an Optional.
Args:
- copy (
Self): TheOptionalto 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): TheNonevalue 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): TheNonevalue 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: