Enum Result

enum Result<T, E>

Result is a type that represents either success (Ok) or failure (Err).

See the module documentation for details.

Variants

Ok(T)

Contains the success value

Err(E)

Contains the error value

Implementations

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

const fn copied(self: Self) -> Result<T, E>
where
    T: Copy

Maps a Result<&T, E> to a Result<T, E> by copying the contents of the Ok part.

Examples

let val = 12;
let x: Result<&i32, i32> = Ok(&val);
assert_eq!(x, Ok(&12));
let copied = x.copied();
assert_eq!(copied, Ok(12));
fn cloned(self: Self) -> Result<T, E>
where
    T: Clone

Maps a Result<&T, E> to a Result<T, E> by cloning the contents of the Ok part.

Examples

let val = 12;
let x: Result<&i32, i32> = Ok(&val);
assert_eq!(x, Ok(&12));
let cloned = x.cloned();
assert_eq!(cloned, Ok(12));

impl<T, E> Result<&mut T, E>

const fn copied(self: Self) -> Result<T, E>
where
    T: Copy

Maps a Result<&mut T, E> to a Result<T, E> by copying the contents of the Ok part.

Examples

let mut val = 12;
let x: Result<&mut i32, i32> = Ok(&mut val);
assert_eq!(x, Ok(&mut 12));
let copied = x.copied();
assert_eq!(copied, Ok(12));
fn cloned(self: Self) -> Result<T, E>
where
    T: Clone

Maps a Result<&mut T, E> to a Result<T, E> by cloning the contents of the Ok part.

Examples

let mut val = 12;
let x: Result<&mut i32, i32> = Ok(&mut val);
assert_eq!(x, Ok(&mut 12));
let cloned = x.cloned();
assert_eq!(cloned, Ok(12));

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

const fn transpose(self: Self) -> Option<Result<T, E>>

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

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

Examples

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

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

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

const fn flatten(self: Self) -> Result<T, E>

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

Examples

let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
assert_eq!(Ok("hello"), x.flatten());

let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
assert_eq!(Err(6), x.flatten());

let x: Result<Result<&'static str, u32>, u32> = Err(6);
assert_eq!(Err(6), x.flatten());

Flattening only removes one level of nesting at a time:

let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
assert_eq!(Ok(Ok("hello")), x.flatten());
assert_eq!(Ok("hello"), x.flatten().flatten());

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

const fn is_ok(self: &Self) -> bool

Returns true if the result is Ok.

Examples

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);
const fn is_ok_and<F>(self: Self, f: F) -> bool
where
    F: ~const FnOnce(T) -> bool,
    T: ,
    E: 

Returns true if the result is Ok and the value inside of it matches a predicate.

Examples

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

let x: Result<u32, &str> = Ok(0);
assert_eq!(x.is_ok_and(|x| x > 1), false);

let x: Result<u32, &str> = Err("hey");
assert_eq!(x.is_ok_and(|x| x > 1), false);

let x: Result<String, &str> = Ok("ownership".to_string());
assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true);
println!("still alive {:?}", x);
const fn is_err(self: &Self) -> bool

Returns true if the result is Err.

Examples

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);
const fn is_err_and<F>(self: Self, f: F) -> bool
where
    F: ~const FnOnce(E) -> bool,
    E: ,
    T: 

Returns true if the result is Err and the value inside of it matches a predicate.

Examples

use std::io::{Error, ErrorKind};

let x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, "!"));
assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);

let x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, "!"));
assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);

let x: Result<u32, Error> = Ok(123);
assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);

let x: Result<u32, String> = Err("ownership".to_string());
assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true);
println!("still alive {:?}", x);
const fn ok(self: Self) -> Option<T>
where
    T: ,
    E: 

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

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

Examples

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);
const fn err(self: Self) -> Option<E>
where
    T: ,
    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

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"));
const fn as_ref(self: &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

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"));
const fn as_mut(self: &mut Self) -> Result<&mut T, &mut E>

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

Examples

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);
const fn map<U, F>(self: Self, op: F) -> Result<U, E>
where
    F: ~const 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(..) => {}
    }
}
const fn map_or<U, F>(self: Self, default: U, f: F) -> U
where
    F: ~const FnOnce(T) -> U,
    T: ,
    E: ,
    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);
const fn map_or_else<U, D, F>(self: Self, default: D, f: F) -> U
where
    D: ~const FnOnce(E) -> U,
    F: ~const 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

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);
const fn map_or_default<U, F>(self: Self, f: F) -> U
where
    F: ~const FnOnce(T) -> U,
    U: ~const Default,
    T: ,
    E: 

Maps a Result<T, E> to a U by applying function f to the contained value if the result is Ok, otherwise if Err, returns the default value for the type U.

Examples

#![feature(result_option_map_or_default)]

let x: Result<_, &str> = Ok("foo");
let y: Result<&str, _> = Err("bar");

assert_eq!(x.map_or_default(|x| x.len()), 3);
assert_eq!(y.map_or_default(|y| y.len()), 0);
const fn map_err<F, O>(self: Self, op: O) -> Result<T, F>
where
    O: ~const 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

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()));
const fn inspect<F>(self: Self, f: F) -> Self
where
    F: ~const FnOnce(&T)

Calls a function with a reference to the contained value if Ok.

Returns the original result.

Examples

let x: u8 = "4"
    .parse::<u8>()
    .inspect(|x| println!("original: {x}"))
    .map(|x| x.pow(3))
    .expect("failed to parse number");
const fn inspect_err<F>(self: Self, f: F) -> Self
where
    F: ~const FnOnce(&E)

Calls a function with a reference to the contained value if Err.

Returns the original result.

Examples

use std::{fs, io};

fn read() -> io::Result<String> {
    fs::read_to_string("address.txt")
        .inspect_err(|e| eprintln!("failed to read file: {e}"))
}
const fn as_deref(self: &Self) -> Result<&<T as >::Target, &E>
where
    T: ~const Deref

Converts from Result<T, E> (or &Result<T, E>) to Result<&<T as Deref>::Target, &E>.

Coerces the Ok variant of the original Result via Deref and returns the new Result.

Examples

let x: Result<String, u32> = Ok("hello".to_string());
let y: Result<&str, &u32> = Ok("hello");
assert_eq!(x.as_deref(), y);

let x: Result<String, u32> = Err(42);
let y: Result<&str, &u32> = Err(&42);
assert_eq!(x.as_deref(), y);
const fn as_deref_mut(self: &mut Self) -> Result<&mut <T as >::Target, &mut E>
where
    T: ~const DerefMut

Converts from Result<T, E> (or &mut Result<T, E>) to Result<&mut <T as DerefMut>::Target, &mut E>.

Coerces the Ok variant of the original Result via DerefMut and returns the new Result.

Examples

let mut s = "HELLO".to_string();
let mut x: Result<String, u32> = Ok("hello".to_string());
let y: Result<&mut str, &mut u32> = Ok(&mut s);
assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);

let mut i = 42;
let mut x: Result<String, u32> = Err(42);
let y: Result<&mut str, &mut u32> = Err(&mut i);
assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
const fn iter(self: &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

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);
const fn iter_mut(self: &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

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);
fn expect(self: Self, msg: &str) -> T
where
    E: fmt::Debug

Returns the contained Ok value, consuming the self value.

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

Panics

Panics if the value is an Err, with a panic message including the passed message, and the content of the Err.

Examples

let x: Result<u32, &str> = Err("emergency failure");
x.expect("Testing expect"); // panics with `Testing expect: emergency failure`

Recommended Message Style

We recommend that expect messages are used to describe the reason you expect the Result should be Ok.

let path = std::env::var("IMPORTANT_PATH")
    .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`");

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 unwrap(self: Self) -> T
where
    E: fmt::Debug

Returns the contained Ok value, consuming the self value.

Because this function may panic, its use is generally discouraged. Panics are meant for unrecoverable errors, and may abort the entire program.

Instead, prefer to use the ? (try) operator, or pattern matching to handle the Err case explicitly, or call unwrap_or, unwrap_or_else, or unwrap_or_default.

Panics

Panics if the value is an Err, with a panic message provided by the Err's value.

Examples

Basic usage:

let x: Result<u32, &str> = Ok(2);
assert_eq!(x.unwrap(), 2);
let x: Result<u32, &str> = Err("emergency failure");
x.unwrap(); // panics with `emergency failure`
const fn unwrap_or_default(self: Self) -> T
where
    T: ~const Default,
    E: 

Returns the contained Ok value or a default

Consumes the self argument then, if Ok, returns the contained value, otherwise if Err, 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 an Err on error.

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

assert_eq!(1909, good_year);
assert_eq!(0, bad_year);
fn expect_err(self: Self, msg: &str) -> E
where
    T: fmt::Debug

Returns the contained Err value, consuming the self value.

Panics

Panics if the value is an Ok, with a panic message including the passed message, and the content of the Ok.

Examples

let x: Result<u32, &str> = Ok(10);
x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
fn unwrap_err(self: Self) -> E
where
    T: fmt::Debug

Returns the contained Err value, consuming the self value.

Panics

Panics if the value is an Ok, with a custom panic message provided by the Ok's value.

Examples

let x: Result<u32, &str> = Ok(2);
x.unwrap_err(); // panics with `2`
let x: Result<u32, &str> = Err("emergency failure");
assert_eq!(x.unwrap_err(), "emergency failure");
const fn into_ok(self: Self) -> T
where
    E: ~const Into<never>

Returns the contained Ok value, but never panics.

Unlike unwrap, this method is known to never panic on the result types it is implemented for. Therefore, it can be used instead of unwrap as a maintainability safeguard that will fail to compile if the error type of the Result is later changed to an error that can actually occur.

Examples

# #![feature(never_type)]
# #![feature(unwrap_infallible)]

fn only_good_news() -> Result<String, !> {
    Ok("this is fine".into())
}

let s: String = only_good_news().into_ok();
println!("{s}");
const fn into_err(self: Self) -> E
where
    T: ~const Into<never>

Returns the contained Err value, but never panics.

Unlike unwrap_err, this method is known to never panic on the result types it is implemented for. Therefore, it can be used instead of unwrap_err as a maintainability safeguard that will fail to compile if the ok type of the Result is later changed to a type that can actually occur.

Examples

# #![feature(never_type)]
# #![feature(unwrap_infallible)]

fn only_bad_news() -> Result<!, String> {
    Err("Oops, it failed".into())
}

let error: String = only_bad_news().into_err();
println!("{error}");
const fn and<U>(self: Self, res: Result<U, E>) -> Result<U, E>
where
    T: ,
    E: ,
    U: 

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

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

Examples

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"));
const fn and_then<U, F>(self: Self, op: F) -> Result<U, E>
where
    F: ~const 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

fn sq_then_to_string(x: u32) -> Result<String, &'static str> {
    x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed")
}

assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));
assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed"));
assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number"));

Often used to chain fallible operations that may return Err.

use std::{io::ErrorKind, path::Path};

// Note: on Windows "/" maps to "C:\"
let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified());
assert!(root_modified_time.is_ok());

let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified());
assert!(should_fail.is_err());
assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
const fn or<F>(self: Self, res: Result<T, F>) -> Result<T, F>
where
    T: ,
    E: ,
    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

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));
const fn or_else<F, O>(self: Self, op: O) -> Result<T, F>
where
    O: ~const 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

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));
const fn unwrap_or(self: Self, default: T) -> T
where
    T: ,
    E: 

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

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);
const fn unwrap_or_else<F>(self: Self, op: F) -> T
where
    F: ~const FnOnce(E) -> T

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

Examples

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);
unsafe const fn unwrap_unchecked(self: 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);
let x: Result<u32, &str> = Err("emergency failure");
unsafe { x.unwrap_unchecked() }; // Undefined behavior!
unsafe fn unwrap_err_unchecked(self: 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!
let x: Result<u32, &str> = Err("emergency failure");
assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");

impl<A, E, V: FromIterator<A>> FromIterator for Result<V, E>

fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E>

Takes each element in the Iterator: if it is an Err, no further elements are taken, and the Err is returned. Should no Err occur, a container with the values of each Result is returned.

Here is an example which increments every integer in a vector, checking for overflow:

let v = vec![1, 2];
let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
    x.checked_add(1).ok_or("Overflow!")
).collect();
assert_eq!(res, Ok(vec![2, 3]));

Here is another example that tries to subtract one from another list of integers, this time checking for underflow:

let v = vec![1, 2, 0];
let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
    x.checked_sub(1).ok_or("Underflow!")
).collect();
assert_eq!(res, Err("Underflow!"));

Here is a variation on the previous example, showing that no further elements are taken from iter after the first Err.

let v = vec![3, 2, 1, 10];
let mut shared = 0;
let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
    shared += x;
    x.checked_sub(2).ok_or("Underflow!")
}).collect();
assert_eq!(res, Err("Underflow!"));
assert_eq!(shared, 6);

Since the third element caused an underflow, no further elements were taken, so the final value of shared is 6 (= 3 + 2 + 1), not 16.

impl<T> Any for Result<T, E>

fn type_id(self: &Self) -> TypeId

impl<T> Borrow for Result<T, E>

fn borrow(self: &Self) -> &T

impl<T> BorrowMut for Result<T, E>

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

impl<T> CloneToUninit for Result<T, E>

unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)

impl<T> From for Result<T, E>

fn from(t: T) -> T

Returns the argument unchanged.

impl<T, E> Clone for Result<T, E>

fn clone(self: &Self) -> Self
fn clone_from(self: &mut Self, source: &Self)

impl<T, E> Freeze for Result<T, E>

impl<T, E> IntoIterator for Result<T, E>

fn into_iter(self: Self) -> IntoIter<T>

Returns a consuming iterator over the possibly contained value.

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

Examples

let x: Result<u32, &str> = Ok(5);
let v: Vec<u32> = x.into_iter().collect();
assert_eq!(v, [5]);

let x: Result<u32, &str> = Err("nothing!");
let v: Vec<u32> = x.into_iter().collect();
assert_eq!(v, []);

impl<T, E> RefUnwindSafe for Result<T, E>

impl<T, E> Residual for Result<convert::Infallible, E>

impl<T, E> Send for Result<T, E>

impl<T, E> StructuralPartialEq for Result<T, E>

impl<T, E> Sync for Result<T, E>

impl<T, E> Try for Result<T, E>

fn from_output(output: <Self as >::Output) -> Self
fn branch(self: Self) -> ControlFlow<<Self as >::Residual, <Self as >::Output>

impl<T, E> Unpin for Result<T, E>

impl<T, E> UnwindSafe for Result<T, E>

impl<T, E> UseCloned for Result<T, E>

impl<T, E, F: ~const From<E>> FromResidual for Result<T, F>

fn from_residual(residual: Result<convert::Infallible, E>) -> Self

impl<T, E, F: ~const From<E>> FromResidual for Result<T, F>

fn from_residual(ops::Yeet: ops::Yeet<E>) -> Self

impl<T, U> Into for Result<T, E>

fn into(self: Self) -> U

Calls U::from(self).

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

impl<T, U> TryFrom for Result<T, E>

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

impl<T, U> TryInto for Result<T, E>

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

impl<T, U, E> Product for Result<T, E>

fn product<I>(iter: I) -> Result<T, E>
where
    I: Iterator<Item = Result<U, E>>

Takes each element in the [Iterator]: if it is an Err, no further elements are taken, and the Err is returned. Should no Err occur, the product of all elements is returned.

Examples

This multiplies each number in a vector of strings, if a string could not be parsed the operation returns Err:

let nums = vec!["5", "10", "1", "2"];
let total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();
assert_eq!(total, Ok(100));
let nums = vec!["5", "10", "one", "2"];
let total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();
assert!(total.is_err());

impl<T, U, E> Sum for Result<T, E>

fn sum<I>(iter: I) -> Result<T, E>
where
    I: Iterator<Item = Result<U, E>>

Takes each element in the [Iterator]: if it is an Err, no further elements are taken, and the Err is returned. Should no Err occur, the sum of all elements is returned.

Examples

This sums up every integer in a vector, rejecting the sum if a negative element is encountered:

let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) };
let v = vec![1, 2];
let res: Result<i32, _> = v.iter().map(f).sum();
assert_eq!(res, Ok(3));
let v = vec![1, -2];
let res: Result<i32, _> = v.iter().map(f).sum();
assert_eq!(res, Err("Negative element found"));

impl<T: $crate::fmt::Debug, E: $crate::fmt::Debug> Debug for Result<T, E>

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

impl<T: $crate::hash::Hash, E: $crate::hash::Hash> Hash for Result<T, E>

fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H)

impl<T: $crate::marker::Copy, E: $crate::marker::Copy> Copy for Result<T, E>

impl<T: CloneFromCell, E: CloneFromCell> CloneFromCell for Result<T, E>

impl<T: ~const $crate::cmp::Eq, E: ~const $crate::cmp::Eq> Eq for Result<T, E>

impl<T: ~const $crate::cmp::Ord, E: ~const $crate::cmp::Ord> Ord for Result<T, E>

fn cmp(self: &Self, other: &Result<T, E>) -> $crate::cmp::Ordering

impl<T: ~const $crate::cmp::PartialEq, E: ~const $crate::cmp::PartialEq> PartialEq for Result<T, E>

fn eq(self: &Self, other: &Result<T, E>) -> bool

impl<T: ~const $crate::cmp::PartialOrd, E: ~const $crate::cmp::PartialOrd> PartialOrd for Result<T, E>

fn partial_cmp(self: &Self, other: &Result<T, E>) -> $crate::option::Option<$crate::cmp::Ordering>