pub enum COption<T> {
    None,
    Some(T),
}
Expand description

A C representation of Rust’s std::option::Option

Variants§

§

None

No value

§

Some(T)

Some value T

Implementations§

source§

impl<T> COption<T>

source

pub fn is_some(&self) -> bool

Returns true if the option is a COption::Some value.

Examples
let x: COption<u32> = COption::Some(2);
assert_eq!(x.is_some(), true);

let x: COption<u32> = COption::None;
assert_eq!(x.is_some(), false);
source

pub fn is_none(&self) -> bool

Returns true if the option is a COption::None value.

Examples
let x: COption<u32> = COption::Some(2);
assert_eq!(x.is_none(), false);

let x: COption<u32> = COption::None;
assert_eq!(x.is_none(), true);
source

pub fn contains<U>(&self, x: &U) -> boolwhere U: PartialEq<T>,

Returns true if the option is a COption::Some value containing the given value.

Examples
#![feature(option_result_contains)]

let x: COption<u32> = COption::Some(2);
assert_eq!(x.contains(&2), true);

let x: COption<u32> = COption::Some(3);
assert_eq!(x.contains(&2), false);

let x: COption<u32> = COption::None;
assert_eq!(x.contains(&2), false);
source

pub fn as_ref(&self) -> COption<&T>

Converts from &COption<T> to COption<&T>.

Examples

Converts an COption<String> into an COption<usize>, preserving the original. The map method takes the self argument by value, consuming the original, so this technique uses as_ref to first take an COption to a reference to the value inside the original.

let text: COption<String> = COption::Some("Hello, world!".to_string());
// First, cast `COption<String>` to `COption<&String>` with `as_ref`,
// then consume *that* with `map`, leaving `text` on the stack.
let text_length: COption<usize> = text.as_ref().map(|s| s.len());
println!("still can print text: {:?}", text);
source

pub fn as_mut(&mut self) -> COption<&mut T>

Converts from &mut COption<T> to COption<&mut T>.

Examples
let mut x = COption::Some(2);
match x.as_mut() {
    COption::Some(v) => *v = 42,
    COption::None => {},
}
assert_eq!(x, COption::Some(42));
source

pub fn expect(self, msg: &str) -> T

Unwraps an option, yielding the content of a COption::Some.

Panics

Panics if the value is a COption::None with a custom panic message provided by msg.

Examples
let x = COption::Some("value");
assert_eq!(x.expect("the world is ending"), "value");
let x: COption<&str> = COption::None;
x.expect("the world is ending"); // panics with `the world is ending`
source

pub fn unwrap(self) -> T

Moves the value v out of the COption<T> if it is COption::Some(v).

In general, because this function may panic, its use is discouraged. Instead, prefer to use pattern matching and handle the COption::None case explicitly.

Panics

Panics if the self value equals COption::None.

Examples
let x = COption::Some("air");
assert_eq!(x.unwrap(), "air");
let x: COption<&str> = COption::None;
assert_eq!(x.unwrap(), "air"); // fails
source

pub fn unwrap_or(self, def: T) -> T

Returns the contained value or a 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!(COption::Some("car").unwrap_or("bike"), "car");
assert_eq!(COption::None.unwrap_or("bike"), "bike");
source

pub fn unwrap_or_else<F>(self, f: F) -> Twhere F: FnOnce() -> T,

Returns the contained value or computes it from a closure.

Examples
let k = 10;
assert_eq!(COption::Some(4).unwrap_or_else(|| 2 * k), 4);
assert_eq!(COption::None.unwrap_or_else(|| 2 * k), 20);
source

pub fn map<U, F>(self, f: F) -> COption<U>where F: FnOnce(T) -> U,

Maps an COption<T> to COption<U> by applying a function to a contained value.

Examples

Converts an COption<String> into an COption<usize>, consuming the original:

let maybe_some_string = COption::Some(String::from("Hello, World!"));
// `COption::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, COption::Some(13));
source

pub fn map_or<U, F>(self, default: U, f: F) -> Uwhere F: FnOnce(T) -> U,

Applies a function to the contained value (if any), or returns the provided default (if not).

Examples
let x = COption::Some("foo");
assert_eq!(x.map_or(42, |v| v.len()), 3);

let x: COption<&str> = COption::None;
assert_eq!(x.map_or(42, |v| v.len()), 42);
source

pub fn map_or_else<U, D, F>(self, default: D, f: F) -> Uwhere D: FnOnce() -> U, F: FnOnce(T) -> U,

Applies a function to the contained value (if any), or computes a default (if not).

Examples
let k = 21;

let x = COption::Some("foo");
assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);

let x: COption<&str> = COption::None;
assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
source

pub fn ok_or<E>(self, err: E) -> Result<T, E>

Transforms the COption<T> into a Result<T, E>, mapping COption::Some(v) to Ok(v) and COption::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 = COption::Some("foo");
assert_eq!(x.ok_or(0), Ok("foo"));

let x: COption<&str> = COption::None;
assert_eq!(x.ok_or(0), Err(0));
source

pub fn ok_or_else<E, F>(self, err: F) -> Result<T, E>where F: FnOnce() -> E,

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

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

let x: COption<&str> = COption::None;
assert_eq!(x.ok_or_else(|| 0), Err(0));
source

pub fn and<U>(self, optb: COption<U>) -> COption<U>

Returns COption::None if the option is COption::None, otherwise returns optb.

Examples
let x = COption::Some(2);
let y: COption<&str> = COption::None;
assert_eq!(x.and(y), COption::None);

let x: COption<u32> = COption::None;
let y = COption::Some("foo");
assert_eq!(x.and(y), COption::None);

let x = COption::Some(2);
let y = COption::Some("foo");
assert_eq!(x.and(y), COption::Some("foo"));

let x: COption<u32> = COption::None;
let y: COption<&str> = COption::None;
assert_eq!(x.and(y), COption::None);
source

pub fn and_then<U, F>(self, f: F) -> COption<U>where F: FnOnce(T) -> COption<U>,

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

COption::Some languages call this operation flatmap.

Examples
fn sq(x: u32) -> COption<u32> { COption::Some(x * x) }
fn nope(_: u32) -> COption<u32> { COption::None }

assert_eq!(COption::Some(2).and_then(sq).and_then(sq), COption::Some(16));
assert_eq!(COption::Some(2).and_then(sq).and_then(nope), COption::None);
assert_eq!(COption::Some(2).and_then(nope).and_then(sq), COption::None);
assert_eq!(COption::None.and_then(sq).and_then(sq), COption::None);
source

pub fn filter<P>(self, predicate: P) -> COption<T>where P: FnOnce(&T) -> bool,

Returns COption::None if the option is COption::None, otherwise calls predicate with the wrapped value and returns:

This function works similar to Iterator::filter(). You can imagine the COption<T> being an iterator over one or zero elements. filter() lets you decide which elements to keep.

Examples
fn is_even(n: &i32) -> bool {
    n % 2 == 0
}

assert_eq!(COption::None.filter(is_even), COption::None);
assert_eq!(COption::Some(3).filter(is_even), COption::None);
assert_eq!(COption::Some(4).filter(is_even), COption::Some(4));
source

pub fn or(self, optb: COption<T>) -> COption<T>

Returns the option if it contains a value, otherwise returns optb.

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

Examples
let x = COption::Some(2);
let y = COption::None;
assert_eq!(x.or(y), COption::Some(2));

let x = COption::None;
let y = COption::Some(100);
assert_eq!(x.or(y), COption::Some(100));

let x = COption::Some(2);
let y = COption::Some(100);
assert_eq!(x.or(y), COption::Some(2));

let x: COption<u32> = COption::None;
let y = COption::None;
assert_eq!(x.or(y), COption::None);
source

pub fn or_else<F>(self, f: F) -> COption<T>where F: FnOnce() -> COption<T>,

Returns the option if it contains a value, otherwise calls f and returns the result.

Examples
fn nobody() -> COption<&'static str> { COption::None }
fn vikings() -> COption<&'static str> { COption::Some("vikings") }

assert_eq!(COption::Some("barbarians").or_else(vikings), COption::Some("barbarians"));
assert_eq!(COption::None.or_else(vikings), COption::Some("vikings"));
assert_eq!(COption::None.or_else(nobody), COption::None);
source

pub fn xor(self, optb: COption<T>) -> COption<T>

Returns COption::Some if exactly one of self, optb is COption::Some, otherwise returns COption::None.

Examples
let x = COption::Some(2);
let y: COption<u32> = COption::None;
assert_eq!(x.xor(y), COption::Some(2));

let x: COption<u32> = COption::None;
let y = COption::Some(2);
assert_eq!(x.xor(y), COption::Some(2));

let x = COption::Some(2);
let y = COption::Some(2);
assert_eq!(x.xor(y), COption::None);

let x: COption<u32> = COption::None;
let y: COption<u32> = COption::None;
assert_eq!(x.xor(y), COption::None);
source

pub fn get_or_insert(&mut self, v: T) -> &mut T

Inserts v into the option if it is COption::None, then returns a mutable reference to the contained value.

Examples
let mut x = COption::None;

{
    let y: &mut u32 = x.get_or_insert(5);
    assert_eq!(y, &5);

    *y = 7;
}

assert_eq!(x, COption::Some(7));
source

pub fn get_or_insert_with<F>(&mut self, f: F) -> &mut Twhere F: FnOnce() -> T,

Inserts a value computed from f into the option if it is COption::None, then returns a mutable reference to the contained value.

Examples
let mut x = COption::None;

{
    let y: &mut u32 = x.get_or_insert_with(|| 5);
    assert_eq!(y, &5);

    *y = 7;
}

assert_eq!(x, COption::Some(7));
source

pub fn replace(&mut self, value: T) -> COption<T>

Replaces the actual value in the option by the value given in parameter, returning the old value if present, leaving a COption::Some in its place without deinitializing either one.

Examples
let mut x = COption::Some(2);
let old = x.replace(5);
assert_eq!(x, COption::Some(5));
assert_eq!(old, COption::Some(2));

let mut x = COption::None;
let old = x.replace(3);
assert_eq!(x, COption::Some(3));
assert_eq!(old, COption::None);
source§

impl<T> COption<&T>where T: Copy,

source

pub fn copied(self) -> COption<T>

Maps an COption<&T> to an COption<T> by copying the contents of the option.

Examples
let x = 12;
let opt_x = COption::Some(&x);
assert_eq!(opt_x, COption::Some(&12));
let copied = opt_x.copied();
assert_eq!(copied, COption::Some(12));
source§

impl<T> COption<&mut T>where T: Copy,

source

pub fn copied(self) -> COption<T>

Maps an COption<&mut T> to an COption<T> by copying the contents of the option.

Examples
let mut x = 12;
let opt_x = COption::Some(&mut x);
assert_eq!(opt_x, COption::Some(&mut 12));
let copied = opt_x.copied();
assert_eq!(copied, COption::Some(12));
source§

impl<T> COption<&T>where T: Clone,

source

pub fn cloned(self) -> COption<T>

Maps an COption<&T> to an COption<T> by cloning the contents of the option.

Examples
let x = 12;
let opt_x = COption::Some(&x);
assert_eq!(opt_x, COption::Some(&12));
let cloned = opt_x.cloned();
assert_eq!(cloned, COption::Some(12));
source§

impl<T> COption<&mut T>where T: Clone,

source

pub fn cloned(self) -> COption<T>

Maps an COption<&mut T> to an COption<T> by cloning the contents of the option.

Examples
let mut x = 12;
let opt_x = COption::Some(&mut x);
assert_eq!(opt_x, COption::Some(&mut 12));
let cloned = opt_x.cloned();
assert_eq!(cloned, COption::Some(12));
source§

impl<T> COption<T>where T: Default,

source

pub fn unwrap_or_default(self) -> T

Returns the contained value or a default

Consumes the self argument then, if COption::Some, returns the contained value, otherwise if COption::None, returns the default value for that type.

Examples

Converts a string to an integer, turning poorly-formed strings into 0 (the default value for integers). parse converts a string to any other type that implements FromStr, returning COption::None on error.

let good_year_from_input = "1909";
let bad_year_from_input = "190blarg";
let good_year = good_year_from_input.parse().ok().unwrap_or_default();
let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();

assert_eq!(1909, good_year);
assert_eq!(0, bad_year);
source§

impl<T> COption<T>where T: Deref,

source

pub fn as_deref(&self) -> COption<&<T as Deref>::Target>

Converts from COption<T> (or &COption<T>) to COption<&T::Target>.

Leaves the original COption in-place, creating a new one with a reference to the original one, additionally coercing the contents via Deref.

Examples
#![feature(inner_deref)]

let x: COption<String> = COption::Some("hey".to_owned());
assert_eq!(x.as_deref(), COption::Some("hey"));

let x: COption<String> = COption::None;
assert_eq!(x.as_deref(), COption::None);
source§

impl<T> COption<T>where T: DerefMut,

source

pub fn as_deref_mut(&mut self) -> COption<&mut <T as Deref>::Target>

Converts from COption<T> (or &mut COption<T>) to COption<&mut T::Target>.

Leaves the original COption in-place, creating a new one containing a mutable reference to the inner type’s Deref::Target type.

Examples
#![feature(inner_deref)]

let mut x: COption<String> = COption::Some("hey".to_owned());
assert_eq!(x.as_deref_mut().map(|x| {
    x.make_ascii_uppercase();
    x
}), COption::Some("HEY".to_owned().as_mut_str()));
source§

impl<T, E> COption<Result<T, E>>

source

pub fn transpose(self) -> Result<COption<T>, E>

Transposes an COption of a Result into a Result of an COption.

COption::None will be mapped to Ok(COption::None). COption::Some(Ok(_)) and COption::Some(Err(_)) will be mapped to Ok(COption::Some(_)) and Err(_).

Examples
#[derive(Debug, Eq, PartialEq)]
struct COption::SomeErr;

let x: Result<COption<i32>, COption::SomeErr> = Ok(COption::Some(5));
let y: COption<Result<i32, COption::SomeErr>> = COption::Some(Ok(5));
assert_eq!(x, y.transpose());
source§

impl<T> COption<COption<T>>

source

pub fn flatten(self) -> COption<T>

Converts from COption<COption<T>> to COption<T>

Examples

Basic usage:

#![feature(option_flattening)]
let x: COption<COption<u32>> = COption::Some(COption::Some(6));
assert_eq!(COption::Some(6), x.flatten());

let x: COption<COption<u32>> = COption::Some(COption::None);
assert_eq!(COption::None, x.flatten());

let x: COption<COption<u32>> = COption::None;
assert_eq!(COption::None, x.flatten());

Flattening once only removes one level of nesting:

#![feature(option_flattening)]
let x: COption<COption<COption<u32>>> = COption::Some(COption::Some(COption::Some(6)));
assert_eq!(COption::Some(COption::Some(6)), x.flatten());
assert_eq!(COption::Some(6), x.flatten().flatten());

Trait Implementations§

source§

impl<T> Clone for COption<T>where T: Clone,

source§

fn clone(&self) -> COption<T>

Returns a copy of the value. Read more
source§

fn clone_from(&mut self, source: &COption<T>)

Performs copy-assignment from source. Read more
source§

impl<T> Debug for COption<T>where T: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<T> Default for COption<T>

source§

fn default() -> COption<T>

Returns COption::None.

Examples
let opt: COption<u32> = COption::default();
assert!(opt.is_none());
source§

impl<'a, T> From<&'a COption<T>> for COption<&'a T>

source§

fn from(o: &'a COption<T>) -> COption<&'a T>

Converts to this type from the input type.
source§

impl<'a, T> From<&'a mut COption<T>> for COption<&'a mut T>

source§

fn from(o: &'a mut COption<T>) -> COption<&'a mut T>

Converts to this type from the input type.
source§

impl<T> From<Option<T>> for COption<T>

source§

fn from(option: Option<T>) -> COption<T>

Converts to this type from the input type.
source§

impl<T> From<T> for COption<T>

source§

fn from(val: T) -> COption<T>

Converts to this type from the input type.
source§

impl<T> Hash for COption<T>where T: Hash,

source§

fn hash<__H>(&self, state: &mut __H)where __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<T> Ord for COption<T>where T: Ord,

source§

fn cmp(&self, other: &COption<T>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Selfwhere Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Selfwhere Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl<T> PartialEq<COption<T>> for COption<T>where T: PartialEq<T>,

source§

fn eq(&self, other: &COption<T>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T> PartialOrd<COption<T>> for COption<T>where T: PartialOrd<T>,

source§

fn partial_cmp(&self, other: &COption<T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<T> Copy for COption<T>where T: Copy,

source§

impl<T> Eq for COption<T>where T: Eq,

source§

impl<T> StructuralEq for COption<T>

source§

impl<T> StructuralPartialEq for COption<T>

Auto Trait Implementations§

§

impl<T> RefUnwindSafe for COption<T>where T: RefUnwindSafe,

§

impl<T> Send for COption<T>where T: Send,

§

impl<T> Sync for COption<T>where T: Sync,

§

impl<T> Unpin for COption<T>where T: Unpin,

§

impl<T> UnwindSafe for COption<T>where T: UnwindSafe,

Blanket Implementations§

source§

impl<T> AbiExample for T

source§

default fn example() -> T

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<!> for T

const: unstable · source§

fn from(t: !) -> T

Converts to this type from the input type.
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same<T> for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V