Enum frame_support::dispatch::result::Result

1.0.0 · source ·
pub enum Result<T, E> {
    Ok(T),
    Err(E),
}
Expand description

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§

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);
🔬This is a nightly-only experimental API. (is_some_and)

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

Examples
#![feature(is_some_and)]

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);

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);
🔬This is a nightly-only experimental API. (is_some_and)

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

Examples
#![feature(is_some_and)]
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);

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);

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"));

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"));

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);

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(..) => {}
    }
}

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);

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);

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()));
🔬This is a nightly-only experimental API. (result_option_inspect)

Calls the provided closure with a reference to the contained value (if Ok).

Examples
#![feature(result_option_inspect)]

let x: u8 = "4"
    .parse::<u8>()
    .inspect(|x| println!("original: {x}"))
    .map(|x| x.pow(3))
    .expect("failed to parse number");
🔬This is a nightly-only experimental API. (result_option_inspect)

Calls the provided closure with a reference to the contained error (if Err).

Examples
#![feature(result_option_inspect)]

use std::{fs, io};

fn read() -> io::Result<String> {
    fs::read_to_string("address.txt")
        .inspect_err(|e| eprintln!("failed to read file: {e}"))
}

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);

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);

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);

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);

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

Basic usage:

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

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.

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 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`

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);

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

Basic usage:

let x: Result<u32, &str> = Ok(10);
x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`

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");
🔬This is a nightly-only experimental API. (unwrap_infallible)

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

Basic usage:


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

let s: String = only_good_news().into_ok();
println!("{s}");
🔬This is a nightly-only experimental API. (unwrap_infallible)

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

Basic usage:


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

let error: String = only_bad_news().into_err();
println!("{error}");

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

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"));

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);

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));

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));

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);

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);

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!

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");
🔬This is a nightly-only experimental API. (option_result_contains)

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);
🔬This is a nightly-only experimental API. (result_contains_err)

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);

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));

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));

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));

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));

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);
🔬This is a nightly-only experimental API. (result_flattening)

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

Examples

Basic usage:

#![feature(result_flattening)]
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:

#![feature(result_flattening)]
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());

Trait Implementations§

The resulting type after applying the + operator.
Performs the + operation. Read more
Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Wrap the error value with additional context.
Wrap the error value with additional context that is evaluated lazily only once an error does occur. Read more
Formats the value using the given formatter. Read more
Attempt to deserialise the value from input.
Attempt to skip the encoded value from input. Read more
Returns the fixed encoded size of the type. Read more
Exactly the same as unwrap_or, but it does the defensive warnings explained in the trait docs. Read more
Exactly the same as unwrap_or_else, but it does the defensive warnings explained in the trait docs. Read more
Exactly the same as unwrap_or_default, but it does the defensive warnings explained in the trait docs. Read more
Does not alter the inner value at all, but it will log warnings if the inner value is None or Err. Read more
Same as Defensive::defensive, but it takes a proof as input, and displays it if the defensive operation has been triggered. Read more
Defensively map the error into another return type, but you are really sure that this conversion should never be needed. Read more
Defensively map and unpack the value to something else (U), or call the default callback if Err, which should never happen. Read more
Defensively transform this result into an option, discarding the Err variant if it happens, which should never happen. Read more
Exactly the same as map, but it prints the appropriate warnings if the value being mapped is Err. Read more
Deserialize this value from the given Serde deserializer. Read more
If possible give a hint of expected size of the encoding. Read more
Convert self to a slice and append it to the destination.
Convert self to an owned vector.
Convert self to a slice and then invoke the given closure with it.
Calculates the encoded size. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.

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.

Collect an arbitrary Result-wrapped collection.

If any item is Err, then all previous Ok items collected are discarded, and it returns that error. If there are multiple errors, the one returned is not deterministic.

Creates an instance of the collection from the parallel iterator par_iter. Read more
🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from a compatible Residual type. Read more
🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from a compatible Residual type. Read more
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more

Returns a consuming 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(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, []);
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
The type of item that the parallel iterator will produce.
The parallel iterator type that will be created.
Converts self into a parallel iterator. Read more
The type of item that the parallel iterator will produce.
The parallel iterator type that will be created.
Converts self into a parallel iterator. Read more
The type of item that the parallel iterator will produce.
The parallel iterator type that will be created.
Converts self into a parallel iterator. Read more
Measure the heap usage of all descendant heap-allocated structures, but not the space taken up by the value itself. If T::size_of is a constant, consider implementing constant_size as well. Read more
Used to optimize MallocSizeOf implementation for collections like Vec and HashMap to avoid iterating over them unnecessarily. The Self: Sized bound is for object safety. Read more
Upper bound, in bytes, of the maximum encoded size of this item.
This method returns an Ordering between self and other. Read more
Compares and returns the maximum of two values. Read more
Compares and returns the minimum of two values. Read more
Restrict a value to a certain interval. Read more
The maximum encoded size for the implementing type. Read more
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
The strategy that should be used to pass the type.

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.

🔬This is a nightly-only experimental API. (try_trait_v2_residual)
The “return” type of this meta-function.
Serialize this value into the given Serde serializer. Read more
The resulting type after applying the - operator.
Performs the - operation. Read more

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 v = vec![1, 2];
let res: Result<i32, &'static str> = v.iter().map(|&x: &i32|
    if x < 0 { Err("Negative element found") }
    else { Ok(x) }
).sum();
assert_eq!(res, Ok(3));
The interior type used to indicate a successful construction.
The interior type used to indicate a failed construction.
Immutably accesses an interior success value. Read more
Mutably accesses an interior success value. Read more
Immutably accesses an interior failure value. Read more
Mutably accesses an interior failure value. Read more
Calls .tap_ok() only in debug builds, and is erased in release builds.
Calls .tap_ok_mut() only in debug builds, and is erased in release builds. Read more
Calls .tap_err() only in debug builds, and is erased in release builds. Read more
Calls .tap_err_mut() only in debug builds, and is erased in release builds. Read more
Is called to get the representation of the value as status code. This status code is returned to the operating system. Read more
🔬This is a nightly-only experimental API. (try_trait_v2)
The type of the value produced by ? when not short-circuiting.
🔬This is a nightly-only experimental API. (try_trait_v2)
The type of the value passed to FromResidual::from_residual as part of ? when short-circuiting. Read more
🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from its Output type. Read more
🔬This is a nightly-only experimental API. (try_trait_v2)
Used in ? to decide whether the operator should produce a value (because this returned ControlFlow::Continue) or propagate a value back to the caller (because this returned ControlFlow::Break). Read more
The type identifying for which type info is provided. Read more
Returns the static type identifier for Self.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Convert from a value of T into an equivalent instance of Option<Self>. Read more
Consume self to return Some equivalent value of Option<T>. Read more
Converts self into T using Into<T>. Read more
Decode Self and consume all of the given input data. Read more
Decode Self and consume all of the given input data. Read more
Decode Self with the given maximum recursion depth and advance input by the number of bytes consumed. Read more
Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait. Read more
Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait. Read more
Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s. Read more
Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s. Read more
Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait. Read more
Compare self to key and return true if they are equal.
Causes self to use its Binary implementation when Debug-formatted. Read more
Causes self to use its Display implementation when Debug-formatted. Read more
Causes self to use its LowerExp implementation when Debug-formatted. Read more
Causes self to use its LowerHex implementation when Debug-formatted. Read more
Causes self to use its Octal implementation when Debug-formatted. Read more
Causes self to use its Pointer implementation when Debug-formatted. Read more
Causes self to use its UpperExp implementation when Debug-formatted. Read more
Causes self to use its UpperHex implementation when Debug-formatted. Read more
Formats each item in a sequence. Read more

Returns the argument unchanged.

As Self can be an unsized type, it needs to be represented by a sized type at the host. This SelfInstance is the sized type. Read more
Create SelfInstance from the given
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

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

Convert self into a ffi value.
The type of the parallel iterator that will be returned.
The type of item that the parallel iterator will produce. This will typically be an &'data T reference type. Read more
Converts self into a parallel iterator. Read more
The type of iterator that will be created.
The type of item that will be produced; this is typically an &'data mut T reference. Read more
Creates the parallel iterator from self. Read more

Get a reference to the inner from the outer.

Get a mutable reference to the inner from the outer.

Return an encoding of Self prepended by given slice.
Method to launch a heapsize measurement with a fresh state. Read more
Pipes by value. This is generally the method you want to use. Read more
Borrows self and passes that borrow into the pipe function. Read more
Mutably borrows self and passes that borrow into the pipe function. Read more
Borrows self, then passes self.borrow() into the pipe function. Read more
Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Borrows self, then passes self.as_ref() into the pipe function.
Mutably borrows self, then passes self.as_mut() into the pipe function. Read more
Borrows self, then passes self.deref() into the pipe function.
Mutably borrows self, then passes self.deref_mut() into the pipe function. Read more
The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
The ffi type that is used to represent Self.
Should always be Self
Convert from a value of T into an equivalent instance of Self. Read more
Consume self to return an equivalent value of T. Read more
Immutable access to a value. Read more
Mutable access to a value. Read more
Immutable access to the Borrow<B> of a value. Read more
Mutable access to the BorrowMut<B> of a value. Read more
Immutable access to the AsRef<R> view of a value. Read more
Mutable access to the AsMut<R> view of a value. Read more
Immutable access to the Deref::Target of a value. Read more
Mutable access to the Deref::Target of a value. Read more
Calls .tap() only in debug builds, and is erased in release builds.
Calls .tap_mut() only in debug builds, and is erased in release builds. Read more
Calls .tap_borrow() only in debug builds, and is erased in release builds. Read more
Calls .tap_borrow_mut() only in debug builds, and is erased in release builds. Read more
Calls .tap_ref() only in debug builds, and is erased in release builds. Read more
Calls .tap_ref_mut() only in debug builds, and is erased in release builds. Read more
Calls .tap_deref() only in debug builds, and is erased in release builds. Read more
Calls .tap_deref_mut() only in debug builds, and is erased in release builds. Read more
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Attempts to convert self into T using TryInto<T>. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
The counterpart to unchecked_from.
Consume self to return an equivalent value of T.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more