Enum std::option::Option

Overview

Methods

fn expect(self, message: any) -> any

Returns the contained [Some] value, consuming the self value.

Panics

Panics if the value is a [None] with a custom panic message provided by msg.

Examples

let x = Some("value");
assert_eq!(x.expect("fruits are healthy"), "value");
let x = None;
x.expect("fruits are healthy"); // panics with `fruits are healthy`

Recommended Message Style

We recommend that expect messages are used to describe the reason you expect the Option should be Some.

let item = slice.get(0).expect("slice should not be empty");

Hint: If you're having trouble remembering how to phrase expect error messages remember to focus on the word "should" as in "env variable should be set by blah" or "the given binary should be available and executable by the current user".

For more detail on expect message styles and the reasoning behind our recommendation please refer to the section on "Common Message Styles" in the std::error module docs.

fn is_some(self) -> bool

Returns true if the option is a [Some] value.

Examples

let x = Some(2);
assert_eq!(x.is_some(), true);

let x = None;
assert_eq!(x.is_some(), false);
fn is_none(self) -> bool

Returns true if the option is a [None] value.

Examples

let x = Some(2);
assert_eq!(x.is_none(), false);

let x = None;
assert_eq!(x.is_none(), true);
fn iter(self) -> Iter

Construct an iterator over an optional value.

Examples

let value = Some(1);
let it = value.iter();

assert_eq!(Some(1), it.next());
assert_eq!(None, it.next());

let value = None;
let it = value.iter();

assert_eq!(None, it.next());
fn and_then(self, then: Function) -> Option

Returns [None] if the option is [None], otherwise calls f with the wrapped value and returns the result.

Some languages call this operation flatmap.

Examples

fn sq_then_to_string(x) {
   x.checked_mul(x).map(|sq| sq.to_string())
}

assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string()));
assert_eq!(Some(1_000_000_000_000_000_000).and_then(sq_then_to_string), None); // overflowed!
assert_eq!(None.and_then(sq_then_to_string), None);

Often used to chain fallible operations that may return [None].

let arr_2d = [["A0", "A1"], ["B0", "B1"]];

let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));
assert_eq!(item_0_1, Some("A1"));

let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));
assert_eq!(item_2_0, None);
fn map(self, then: Function) -> Option

Maps an Option<T> to Option<U> by applying a function to a contained value (if Some) or returns None (if None).

Examples

Calculates the length of an Option<[String]> as an Option<[usize]>, consuming the original:

let maybe_some_string = Some(String::from("Hello, World!"));
// `Option::map` takes self *by value*, consuming `maybe_some_string`
let maybe_some_len = maybe_some_string.map(|s| s.len());
assert_eq!(maybe_some_len, Some(13));

let x = None;
assert_eq!(x.map(|s| s.len()), None);
fn take(self) -> Option

Takes the value out of the option, leaving a [None] in its place.

Examples

let x = Some(2);
let y = x.take();
assert_eq!(x, None);
assert_eq!(y, Some(2));

let x = None;
let y = x.take();
assert_eq!(x, None);
assert_eq!(y, None);
fn transpose(self) -> any

Transposes an Option of a [Result] into a [Result] of an Option.

[None] will be mapped to [Ok]\([None]). [Some]\([Ok]\(\_)) and [Some]\([Err]\(\_)) will be mapped to [Ok]\([Some]\(\_)) and [Err]\(\_).

Examples

let x = Ok(Some(5));
let y = Some(Ok(5));
assert_eq!(x, y.transpose());
fn unwrap(self) -> any

Returns the contained [Some] value, consuming the self value.

Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the [None] case explicitly, or call unwrap_or, unwrap_or_else, or unwrap_or_default.

Panics

Panics if the self value equals [None].

Examples

let x = Some("air");
assert_eq!(x.unwrap(), "air");
let x = None;
assert_eq!(x.unwrap(), "air"); // fails
fn unwrap_or(self, default: any) -> any

Returns the contained [Some] value or a provided default.

Arguments passed to unwrap_or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use unwrap_or_else, which is lazily evaluated.

Examples

assert_eq!(Some("car").unwrap_or("bike"), "car");
assert_eq!(None.unwrap_or("bike"), "bike");
fn unwrap_or_else(self, default: Function) -> any

Returns the contained [Some] value or computes it from a closure.

Examples

let k = 10;
assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
fn ok_or(self, err: any) -> Result

Transforms the Option<T> into a [Result<T, E>], mapping Some(v) to Ok(v) and [None] to Err(err).

Arguments passed to ok_or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use ok_or_else, which is lazily evaluated.

Examples

let x = Some("foo");
assert_eq!(x.ok_or(0), Ok("foo"));

let x = None;
assert_eq!(x.ok_or(0), Err(0));

Transforms the Option<T> into a [Result<T, E>], mapping Some(v) to Ok(v) and [None] to Err(err()).

Examples

let x = Some("foo");
assert_eq!(x.ok_or_else(|| 0), Ok("foo"));

let x = None;
assert_eq!(x.ok_or_else(|| 0), Err(0));

Trait Implementations

impl Clone for Option
fn clone(value: any) -> any

Clone the specified value.

Examples

let a = 42;
let b = a;
let c = a.clone();

a += 1;

assert_eq!(a, 43);
assert_eq!(b, 42);
assert_eq!(c, 42);
impl PartialEq for Option
fn eq(value: any, value1: any) -> bool

Compare two values for equality.

Examples

assert_eq!(1.eq(2), false);
assert_eq!(2.eq(2), true);
assert_eq!(2.eq(1), false);
fn ne(value: any, value1: any) -> bool

Compare two values for inequality.

Examples

assert_eq!(1.ne(2), true);
assert_eq!(2.ne(2), false);
assert_eq!(2.ne(1), true);
impl Eq for Option
impl PartialOrd for Option
fn partial_cmp(value: any, value1: any) -> Option

Compare two values.

Examples

use std::cmp::Ordering;

assert_eq!(1.partial_cmp(2), Some(Ordering::Less));
assert_eq!(2.partial_cmp(2), Some(Ordering::Equal));
assert_eq!(2.partial_cmp(1), Some(Ordering::Greater));
fn lt(value: any, value1: any) -> bool

Tests less than (for self and other) and is used by the < operator.

Examples

assert_eq!(1.0 < 1.0, false);
assert_eq!(1.0 < 2.0, true);
assert_eq!(2.0 < 1.0, false);
fn le(value: any, value1: any) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator.

Examples

assert_eq!(1.0 <= 1.0, true);
assert_eq!(1.0 <= 2.0, true);
assert_eq!(2.0 <= 1.0, false);
fn gt(value: any, value1: any) -> bool

Tests greater than (for self and other) and is used by the > operator.

Examples

assert_eq!(1.0 > 1.0, false);
assert_eq!(1.0 > 2.0, false);
assert_eq!(2.0 > 1.0, true);
fn ge(value: any, value1: any) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator.

Examples

assert_eq!(1.0 >= 1.0, true);
assert_eq!(1.0 >= 2.0, false);
assert_eq!(2.0 >= 1.0, true);
impl Ord for Option
fn cmp(value: any, value1: any) -> Ordering

Compare two values.

Examples

use std::cmp::Ordering;

assert_eq!(1.cmp(2), Ordering::Less);
assert_eq!(2.cmp(2), Ordering::Equal);
assert_eq!(2.cmp(1), Ordering::Greater);
fn min(value: any, value1: any) -> Ordering

Return the minimum of two values.

Examples

assert_eq!(1.min(2), 1);
assert_eq!(2.min(2), 2);
assert_eq!(2.min(1), 1);
fn max(value: any, value1: any) -> Ordering

Return the maximum of two values.

Examples

assert_eq!(1.max(2), 2);
assert_eq!(2.max(2), 2);
assert_eq!(2.max(1), 2);

Protocols

protocol IS_VARIANT

Test if the provided argument is a variant.

protocol GET
let $out = value.0

Allows a get operation to work.

protocol INTO_ITER
for item in value { }

Construct an iterator over an optional value.

Examples

let value = Some(1);

let out = [];

for v in value {
   out.push(v);
}

assert_eq!(out, [1]);
protocol CLONE
let $out = clone(value)

Clone the option.

Examples

let a = Some(b"hello world");
let b = a.clone();

a?.extend(b"!");

assert_eq!(a, Some(b"hello world!"));
assert_eq!(b, Some(b"hello world"));
protocol PARTIAL_EQ
if value == b { }

Test two options for partial equality.

Examples

assert!(None == None);
assert!(Some(b"a") == Some(b"a"));
assert!(Some(b"a") != Some(b"ab"));
assert!(Some(b"ab") != Some(b"a"));

Using explicit functions:

use std::ops::partial_eq;

assert_eq!(partial_eq(None, None), true);
assert_eq!(partial_eq(Some(b"a"), Some(b"a")), true);
assert_eq!(partial_eq(Some(b"a"), Some(b"ab")), false);
assert_eq!(partial_eq(Some(b"ab"), Some(b"a")), false);
protocol EQ
if value == b { }

Test two options for total equality.

Examples

use std::ops::eq;

assert_eq!(eq(None, None), true);
assert_eq!(eq(Some(b"a"), Some(b"a")), true);
assert_eq!(eq(Some(b"a"), Some(b"ab")), false);
assert_eq!(eq(Some(b"ab"), Some(b"a")), false);
protocol PARTIAL_CMP
if value < b { }

Perform a partial ordered comparison between two options.

Examples

assert!(Some(b"a") < Some(b"ab"));
assert!(Some(b"ab") > Some(b"a"));
assert!(Some(b"a") == Some(b"a"));

Using explicit functions:

use std::cmp::Ordering;
use std::ops::partial_cmp;

assert_eq!(partial_cmp(Some(b"a"), Some(b"ab")), Some(Ordering::Less));
assert_eq!(partial_cmp(Some(b"ab"), Some(b"a")), Some(Ordering::Greater));
assert_eq!(partial_cmp(Some(b"a"), Some(b"a")), Some(Ordering::Equal));
protocol CMP
if value < b { }

Perform a totally ordered comparison between two options.

Examples

use std::cmp::Ordering;
use std::ops::cmp;

assert_eq!(cmp(Some(b"a"), Some(b"ab")), Ordering::Less);
assert_eq!(cmp(Some(b"ab"), Some(b"a")), Ordering::Greater);
assert_eq!(cmp(Some(b"a"), Some(b"a")), Ordering::Equal);
protocol HASH
let $out = hash(value)

Hash the result.

Examples

use std::ops::hash;

let a = Ok("hello");
let b = Ok("hello");

assert_eq!(hash(a), hash(b));
protocol DEBUG_FMT
format!("{:?}", value)

Write a debug representation of a result.

Examples

println!("{:?}", Some("Hello"));
println!("{:?}", None);
protocol TRY
value?

Using Option with the try protocol.

Examples

fn maybe_add_one(value) {
   Some(value? + 1)
}

assert_eq!(maybe_add_one(Some(4)), Some(5));
assert_eq!(maybe_add_one(None), None);
protocol LT
if $a < $b { }

The protocol behind the < operator.

protocol LE
if $a <= $b { }

The protocol behind the <= operator.

protocol GT
if $a > $b { }

The protocol behind the > operator.

protocol GE
if $a >= $b { }

The protocol behind the >= operator.

protocol MIN
$a.min($b)

The implementation protocol for the PartialOrd::min method.

protocol MAX
$a.max($b)

The implementation protocol for the PartialOrd::max method.