Expand description
A type for optional values.
Type Option
represents an optional value: every Option
is either Some
and contains a value, or None
, and
does not. Option
types are very common in Sway code, as
they have a number of uses:
- Initial values where
None
can be used as an initializer. - Return value for otherwise reporting simple errors, where
None
is
returned on error. - Optional struct fields.
- Optional function arguments.
Option
s are commonly paired with pattern matching to query the presence
of a value and take action, always accounting for the None
case.
fn divide(numerator: u64, denominator: u64) -> Option<u64> {
if denominator == 0 {
None
} else {
Some(numerator / denominator)
}
}
fn call_divide() {
// The return value of the function is an option
let result = divide(6, 2);
// Pattern match to retrieve the value
match result {
// The division was valid
Some(x) => std::logging::log(x),
// The division was invalid
None => std::logging::log("Cannot divide by 0"),
}
}
Method overview
In addition to working with pattern matching, Option
provides a wide
variety of different methods.
Querying the variant
The is_some
and is_none
methods return true
if the Option
is Some
or None
, respectively.
is_none
: Option::is_none
is_some
: Option::is_some
Extracting the contained value
These methods extract the contained value in an Option<T>
when it
is the Some
variant. If the Option
is None
:
unwrap
reverts.unwrap_or
returns the provided default value.
unwrap
: Option::unwrap
unwrap_or
: Option::unwrap_or
Transforming contained values
These methods transform Option
to Result
:
ok_or
transformsSome(v)
toOk(v)
, andNone
to
Err(e)
using the provided default error value.
Err(e)
: Result::Err
Ok(v)
: Result::Ok
Some(v)
: Option::Some
ok_or
: Option::ok_or
Enums
A type that represents an optional value, either Some(val)
or None
.