1

Result in std::result - Rust

 2 years ago
source link: https://doc.rust-lang.org/stable/std/result/enum.Result.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

pub const fn is_ok(&self) -> bool

Returns true if the result is Ok.

Examples

Basic usage:

let x: Result<i32, &str> = Ok(-3);
assert_eq!(x.is_ok(), true);

let x: Result<i32, &str> = Err("Some error message");
assert_eq!(x.is_ok(), false);
Run

pub const fn is_err(&self) -> bool

Returns true if the result is Err.

Examples

Basic usage:

let x: Result<i32, &str> = Ok(-3);
assert_eq!(x.is_err(), false);

let x: Result<i32, &str> = Err("Some error message");
assert_eq!(x.is_err(), true);
Run

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

🔬 This is a nightly-only experimental API. (option_result_contains #62358)

Returns true if the result is an Ok value containing the given value.

Examples
#![feature(option_result_contains)]

let x: Result<u32, &str> = Ok(2);
assert_eq!(x.contains(&2), true);

let x: Result<u32, &str> = Ok(3);
assert_eq!(x.contains(&2), false);

let x: Result<u32, &str> = Err("Some error message");
assert_eq!(x.contains(&2), false);
Run

pub fn contains_err<F>(&self, f: &F) -> bool where
    F: PartialEq<E>, 

🔬 This is a nightly-only experimental API. (result_contains_err #62358)

Returns true if the result is an Err value containing the given value.

Examples
#![feature(result_contains_err)]

let x: Result<u32, &str> = Ok(2);
assert_eq!(x.contains_err(&"Some error message"), false);

let x: Result<u32, &str> = Err("Some error message");
assert_eq!(x.contains_err(&"Some error message"), true);

let x: Result<u32, &str> = Err("Some other error message");
assert_eq!(x.contains_err(&"Some error message"), false);
Run

pub fn ok(self) -> Option<T>

Converts from Result<T, E> to Option<T>.

Converts self into an Option<T>, consuming self, and discarding the error, if any.

Examples

Basic usage:

let x: Result<u32, &str> = Ok(2);
assert_eq!(x.ok(), Some(2));

let x: Result<u32, &str> = Err("Nothing here");
assert_eq!(x.ok(), None);
Run

pub fn err(self) -> Option<E>

Converts from Result<T, E> to Option<E>.

Converts self into an Option<E>, consuming self, and discarding the success value, if any.

Examples

Basic usage:

let x: Result<u32, &str> = Ok(2);
assert_eq!(x.err(), None);

let x: Result<u32, &str> = Err("Nothing here");
assert_eq!(x.err(), Some("Nothing here"));
Run

pub const fn as_ref(&self) -> Result<&T, &E>

Converts from &Result<T, E> to Result<&T, &E>.

Produces a new Result, containing a reference into the original, leaving the original in place.

Examples

Basic usage:

let x: Result<u32, &str> = Ok(2);
assert_eq!(x.as_ref(), Ok(&2));

let x: Result<u32, &str> = Err("Error");
assert_eq!(x.as_ref(), Err(&"Error"));
Run

pub fn as_mut(&mut self) -> Result<&mut T, &mut E>

Converts from &mut Result<T, E> to Result<&mut T, &mut E>.

Examples

Basic usage:

fn mutate(r: &mut Result<i32, i32>) {
    match r.as_mut() {
        Ok(v) => *v = 42,
        Err(e) => *e = 0,
    }
}

let mut x: Result<i32, i32> = Ok(2);
mutate(&mut x);
assert_eq!(x.unwrap(), 42);

let mut x: Result<i32, i32> = Err(13);
mutate(&mut x);
assert_eq!(x.unwrap_err(), 0);
Run

pub fn map<U, F>(self, op: F) -> Result<U, E> where
    F: FnOnce(T) -> U, 

Maps a Result<T, E> to Result<U, E> by applying a function to a contained Ok value, leaving an Err value untouched.

This function can be used to compose the results of two functions.

Examples

Print the numbers on each line of a string multiplied by two.

let line = "1\n2\n3\n4\n";

for num in line.lines() {
    match num.parse::<i32>().map(|i| i * 2) {
        Ok(n) => println!("{}", n),
        Err(..) => {}
    }
}
Run

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

Returns the provided default (if Err), or applies a function to the contained value (if Ok),

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

Examples
let x: Result<_, &str> = Ok("foo");
assert_eq!(x.map_or(42, |v| v.len()), 3);

let x: Result<&str, _> = Err("bar");
assert_eq!(x.map_or(42, |v| v.len()), 42);
Run

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

Maps a Result<T, E> to U by applying fallback function default to a contained Err value, or function f to a contained Ok value.

This function can be used to unpack a successful result while handling an error.

Examples

Basic usage:

let k = 21;

let x : Result<_, &str> = Ok("foo");
assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);

let x : Result<&str, _> = Err("bar");
assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
Run

pub fn map_err<F, O>(self, op: O) -> Result<T, F> where
    O: FnOnce(E) -> F, 

Maps a Result<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched.

This function can be used to pass through a successful result while handling an error.

Examples

Basic usage:

fn stringify(x: u32) -> String { format!("error code: {}", x) }

let x: Result<u32, u32> = Ok(2);
assert_eq!(x.map_err(stringify), Ok(2));

let x: Result<u32, u32> = Err(13);
assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
Run

pub fn iter(&self) -> Iter<'_, T>ⓘ

Returns an iterator over the possibly contained value.

The iterator yields one value if the result is Result::Ok, otherwise none.

Examples

Basic usage:

let x: Result<u32, &str> = Ok(7);
assert_eq!(x.iter().next(), Some(&7));

let x: Result<u32, &str> = Err("nothing!");
assert_eq!(x.iter().next(), None);
Run

pub fn iter_mut(&mut self) -> IterMut<'_, T>ⓘ

Returns a mutable iterator over the possibly contained value.

The iterator yields one value if the result is Result::Ok, otherwise none.

Examples

Basic usage:

let mut x: Result<u32, &str> = Ok(7);
match x.iter_mut().next() {
    Some(v) => *v = 40,
    None => {},
}
assert_eq!(x, Ok(40));

let mut x: Result<u32, &str> = Err("nothing!");
assert_eq!(x.iter_mut().next(), None);
Run

pub fn and<U>(self, res: Result<U, E>) -> Result<U, E>

Returns res if the result is Ok, otherwise returns the Err value of self.

Examples

Basic usage:

let x: Result<u32, &str> = Ok(2);
let y: Result<&str, &str> = Err("late error");
assert_eq!(x.and(y), Err("late error"));

let x: Result<u32, &str> = Err("early error");
let y: Result<&str, &str> = Ok("foo");
assert_eq!(x.and(y), Err("early error"));

let x: Result<u32, &str> = Err("not a 2");
let y: Result<&str, &str> = Err("late error");
assert_eq!(x.and(y), Err("not a 2"));

let x: Result<u32, &str> = Ok(2);
let y: Result<&str, &str> = Ok("different result type");
assert_eq!(x.and(y), Ok("different result type"));
Run

pub fn and_then<U, F>(self, op: F) -> Result<U, E> where
    F: FnOnce(T) -> Result<U, E>, 

Calls op if the result is Ok, otherwise returns the Err value of self.

This function can be used for control flow based on Result values.

Examples

Basic usage:

fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
fn err(x: u32) -> Result<u32, u32> { Err(x) }

assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
Run

pub fn or<F>(self, res: Result<T, F>) -> Result<T, F>

Returns res if the result is Err, otherwise returns the Ok value of self.

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

Basic usage:

let x: Result<u32, &str> = Ok(2);
let y: Result<u32, &str> = Err("late error");
assert_eq!(x.or(y), Ok(2));

let x: Result<u32, &str> = Err("early error");
let y: Result<u32, &str> = Ok(2);
assert_eq!(x.or(y), Ok(2));

let x: Result<u32, &str> = Err("not a 2");
let y: Result<u32, &str> = Err("late error");
assert_eq!(x.or(y), Err("late error"));

let x: Result<u32, &str> = Ok(2);
let y: Result<u32, &str> = Ok(100);
assert_eq!(x.or(y), Ok(2));
Run

pub fn or_else<F, O>(self, op: O) -> Result<T, F> where
    O: FnOnce(E) -> Result<T, F>, 

Calls op if the result is Err, otherwise returns the Ok value of self.

This function can be used for control flow based on result values.

Examples

Basic usage:

fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
fn err(x: u32) -> Result<u32, u32> { Err(x) }

assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
Run

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

Returns the contained Ok 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

Basic usage:

let default = 2;
let x: Result<u32, &str> = Ok(9);
assert_eq!(x.unwrap_or(default), 9);

let x: Result<u32, &str> = Err("error");
assert_eq!(x.unwrap_or(default), default);
Run

pub fn unwrap_or_else<F>(self, op: F) -> T where
    F: FnOnce(E) -> T, 

Returns the contained Ok value or computes it from a closure.

Examples

Basic usage:

fn count(x: &str) -> usize { x.len() }

assert_eq!(Ok(2).unwrap_or_else(count), 2);
assert_eq!(Err("foo").unwrap_or_else(count), 3);
Run

pub unsafe fn unwrap_unchecked(self) -> T

Returns the contained Ok value, consuming the self value, without checking that the value is not an Err.

Safety

Calling this method on an Err is undefined behavior.

Examples
let x: Result<u32, &str> = Ok(2);
assert_eq!(unsafe { x.unwrap_unchecked() }, 2);
Run
let x: Result<u32, &str> = Err("emergency failure");
unsafe { x.unwrap_unchecked(); } // Undefined behavior!
Run

pub unsafe fn unwrap_err_unchecked(self) -> E

Returns the contained Err value, consuming the self value, without checking that the value is not an Ok.

Safety

Calling this method on an Ok is undefined behavior.

Examples
let x: Result<u32, &str> = Ok(2);
unsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
Run
let x: Result<u32, &str> = Err("emergency failure");
assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");
Run

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK