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
impl<T, E> Result<T, E>
source
impl<T, E> Result<T, E>
sourcepub fn is_ok_and(&self, f: impl FnOnce(&T) -> bool) -> bool
source
pub fn is_ok_and(&self, f: impl FnOnce(&T) -> bool) -> bool
sourceReturns true if the result is Ok and the value inside of it matches a predicate.
Examples
#![feature(is_some_with)]
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);Runpub fn is_err_and(&self, f: impl FnOnce(&E) -> bool) -> bool
source
pub fn is_err_and(&self, f: impl FnOnce(&E) -> bool) -> bool
sourceReturns true if the result is Err and the value inside of it matches a predicate.
Examples
#![feature(is_some_with)]
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);Runpub fn err(self) -> Option<E>
const: unstable · source
pub fn err(self) -> Option<E>
const: unstable · sourceConverts 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"));Runpub const fn as_ref(&self) -> Result<&T, &E>
const: 1.48.0 · source
pub const fn as_ref(&self) -> Result<&T, &E>
const: 1.48.0 · sourceConverts 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"));Runpub fn as_mut(&mut self) -> Result<&mut T, &mut E>
const: unstable · source
pub fn as_mut(&mut self) -> Result<&mut T, &mut E>
const: unstable · sourceConverts 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);Runpub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E>
source
pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E>
sourceMaps 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(..) => {}
}
}Runpub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U
1.41.0 · source
pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U
1.41.0 · sourceReturns 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);Runpub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(
self,
default: D,
f: F
) -> U
1.41.0 · source
pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(
self,
default: D,
f: F
) -> U
1.41.0 · sourceMaps 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);Runpub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F>
source
pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F>
sourceMaps 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()));Runpub fn inspect_err<F: FnOnce(&E)>(self, f: F) -> Self
source
pub fn inspect_err<F: FnOnce(&E)>(self, f: F) -> Self
sourcepub fn as_deref(&self) -> Result<&T::Target, &E> where
T: Deref,
1.47.0 · source
pub fn as_deref(&self) -> Result<&T::Target, &E> where
T: Deref,
1.47.0 · sourceConverts 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);Runpub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> where
T: DerefMut,
1.47.0 · source
pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> where
T: DerefMut,
1.47.0 · sourceConverts 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);Runpub fn iter(&self) -> Iter<'_, T>ⓘNotable traits for Iter<'a, T>impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T;
source
pub fn iter(&self) -> Iter<'_, T>ⓘNotable traits for Iter<'a, T>impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T;
sourceReturns 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);Runpub fn iter_mut(&mut self) -> IterMut<'_, T>ⓘNotable traits for IterMut<'a, T>impl<'a, T> Iterator for IterMut<'a, T> type Item = &'a mut T;
source
pub fn iter_mut(&mut self) -> IterMut<'_, T>ⓘNotable traits for IterMut<'a, T>impl<'a, T> Iterator for IterMut<'a, T> type Item = &'a mut T;
sourceReturns 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);Runpub fn expect(self, msg: &str) -> T where
E: Debug,
1.4.0 · source
pub fn expect(self, msg: &str) -> T where
E: Debug,
1.4.0 · sourceReturns the contained Ok value, consuming the self value.
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`Runpub fn unwrap(self) -> T where
E: Debug,
source
pub fn unwrap(self) -> T where
E: Debug,
sourceReturns 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);Runlet x: Result<u32, &str> = Err("emergency failure");
x.unwrap(); // panics with `emergency failure`Runpub fn unwrap_or_default(self) -> T where
T: Default,
1.16.0 · source
pub fn unwrap_or_default(self) -> T where
T: Default,
1.16.0 · sourceReturns 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);Runpub fn expect_err(self, msg: &str) -> E where
T: Debug,
1.17.0 · source
pub fn expect_err(self, msg: &str) -> E where
T: Debug,
1.17.0 · sourceReturns 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`Runpub fn unwrap_err(self) -> E where
T: Debug,
source
pub fn unwrap_err(self) -> E where
T: Debug,
sourceReturns 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`Runlet x: Result<u32, &str> = Err("emergency failure");
assert_eq!(x.unwrap_err(), "emergency failure");Runpub fn into_ok(self) -> T where
E: Into<!>,
source
pub fn into_ok(self) -> T where
E: Into<!>,
sourceReturns 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}");Runpub fn into_err(self) -> E where
T: Into<!>,
source
pub fn into_err(self) -> E where
T: Into<!>,
sourceReturns 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}");Runpub fn and<U>(self, res: Result<U, E>) -> Result<U, E>
const: unstable · source
pub fn and<U>(self, res: Result<U, E>) -> Result<U, E>
const: unstable · sourceReturns 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"));Runpub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E>
source
pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E>
sourceCalls 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"));RunOften 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);Runpub fn or<F>(self, res: Result<T, F>) -> Result<T, F>
const: unstable · source
pub fn or<F>(self, res: Result<T, F>) -> Result<T, F>
const: unstable · sourceReturns 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));Runpub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F>
source
pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F>
sourceCalls 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));Runpub fn unwrap_or(self, default: T) -> T
const: unstable · source
pub fn unwrap_or(self, default: T) -> T
const: unstable · sourceReturns 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);Runpub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T
source
pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T
sourcepub unsafe fn unwrap_unchecked(self) -> T
1.58.0 · source
pub unsafe fn unwrap_unchecked(self) -> T
1.58.0 · sourceReturns 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);Runlet x: Result<u32, &str> = Err("emergency failure");
unsafe { x.unwrap_unchecked(); } // Undefined behavior!Runpub unsafe fn unwrap_err_unchecked(self) -> E
1.58.0 · source
pub unsafe fn unwrap_err_unchecked(self) -> E
1.58.0 · sourceReturns 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!Runlet x: Result<u32, &str> = Err("emergency failure");
assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");Runpub fn contains<U>(&self, x: &U) -> bool where
U: PartialEq<T>,
source
pub fn contains<U>(&self, x: &U) -> bool where
U: PartialEq<T>,
sourceReturns 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);Runpub fn contains_err<F>(&self, f: &F) -> bool where
F: PartialEq<E>,
source
pub fn contains_err<F>(&self, f: &F) -> bool where
F: PartialEq<E>,
sourceReturns 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);Runimpl<T, E> Result<&mut T, E>
source
impl<T, E> Result<&mut T, E>
sourceimpl<T, E> Result<Option<T>, E>
source
impl<T, E> Result<Option<T>, E>
sourcepub fn transpose(self) -> Option<Result<T, E>>
1.33.0 (const: unstable) · source
pub fn transpose(self) -> Option<Result<T, E>>
1.33.0 (const: unstable) · sourceTransposes 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);Runimpl<T, E> Result<Result<T, E>, E>
source
impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
source
pub fn flatten(self) -> Result<T, E>
sourceConverts 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());RunFlattening 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());Runimpl<T> Result<T, T>
source
impl<T> Result<T, T>
sourcepub const fn into_ok_or_err(self) -> T
source
pub const fn into_ok_or_err(self) -> T
sourceReturns the Ok value if self is Ok, and the Err value if
self is Err.
In other words, this function returns the value (the T) of a
Result<T, T>, regardless of whether or not that result is Ok or
Err.
This can be useful in conjunction with APIs such as
Atomic*::compare_exchange, or slice::binary_search, but only in
cases where you don’t care if the result was Ok or not.
Examples
#![feature(result_into_ok_or_err)]
let ok: Result<u32, u32> = Ok(3);
let err: Result<u32, u32> = Err(4);
assert_eq!(ok.into_ok_or_err(), 3);
assert_eq!(err.into_ok_or_err(), 4);RunTrait Implementations
impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E>
source
impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E>
sourcefn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E>
source
fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E>
sourceTakes 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]));RunHere 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!"));RunHere 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);RunSince 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, E, F: From<E>> FromResidual<Result<Infallible, E>> for Result<T, F>
const: unstable · source
impl<T, E, F: From<E>> FromResidual<Result<Infallible, E>> for Result<T, F>
const: unstable · sourcefn from_residual(residual: Result<Infallible, E>) -> Self
const: unstable · source
fn from_residual(residual: Result<Infallible, E>) -> Self
const: unstable · sourceConstructs the type from a compatible Residual type. Read more
impl<T, E, F: From<E>> FromResidual<Result<Infallible, E>> for Poll<Result<T, F>>
source
impl<T, E, F: From<E>> FromResidual<Result<Infallible, E>> for Poll<Result<T, F>>
sourcefn from_residual(x: Result<Infallible, E>) -> Self
source
fn from_residual(x: Result<Infallible, E>) -> Self
sourceConstructs the type from a compatible Residual type. Read more
impl<T, E, F: From<E>> FromResidual<Result<Infallible, E>> for Poll<Option<Result<T, F>>>
source
impl<T, E, F: From<E>> FromResidual<Result<Infallible, E>> for Poll<Option<Result<T, F>>>
sourcefn from_residual(x: Result<Infallible, E>) -> Self
source
fn from_residual(x: Result<Infallible, E>) -> Self
sourceConstructs the type from a compatible Residual type. Read more
impl<T, E, F: From<E>> FromResidual<Yeet<E>> for Result<T, F>
source
impl<T, E, F: From<E>> FromResidual<Yeet<E>> for Result<T, F>
sourcefn from_residual(ops::Yeet: Yeet<E>) -> Self
source
fn from_residual(ops::Yeet: Yeet<E>) -> Self
sourceConstructs the type from a compatible Residual type. Read more
impl<T, E> IntoIterator for Result<T, E>
source
impl<T, E> IntoIterator for Result<T, E>
sourcefn into_iter(self) -> IntoIter<T>ⓘNotable traits for IntoIter<T>impl<T> Iterator for IntoIter<T> type Item = T;
source
fn into_iter(self) -> IntoIter<T>ⓘNotable traits for IntoIter<T>impl<T> Iterator for IntoIter<T> type Item = T;
sourceReturns 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, []);Runtype Item = T
type Item = T
The type of the elements being iterated over.
impl<'a, T, E> IntoIterator for &'a Result<T, E>
1.4.0 · source
impl<'a, T, E> IntoIterator for &'a Result<T, E>
1.4.0 · sourceimpl<'a, T, E> IntoIterator for &'a mut Result<T, E>
1.4.0 · source
impl<'a, T, E> IntoIterator for &'a mut Result<T, E>
1.4.0 · sourceimpl<T: Ord, E: Ord> Ord for Result<T, E>
source
impl<T: Ord, E: Ord> Ord for Result<T, E>
sourcefn max(self, other: Self) -> Self where
Self: Sized,
1.21.0 · source
fn max(self, other: Self) -> Self where
Self: Sized,
1.21.0 · sourceCompares and returns the maximum of two values. Read more
impl<T: PartialOrd, E: PartialOrd> PartialOrd<Result<T, E>> for Result<T, E>
source
impl<T: PartialOrd, E: PartialOrd> PartialOrd<Result<T, E>> for Result<T, E>
sourcefn partial_cmp(&self, other: &Result<T, E>) -> Option<Ordering>
source
fn partial_cmp(&self, other: &Result<T, E>) -> Option<Ordering>
sourceThis method returns an ordering between self and other values if one exists. Read more
fn lt(&self, other: &Rhs) -> bool
source
fn lt(&self, other: &Rhs) -> bool
sourceThis method tests less than (for self and other) and is used by the < operator. Read more
fn le(&self, other: &Rhs) -> bool
source
fn le(&self, other: &Rhs) -> bool
sourceThis method tests less than or equal to (for self and other) and is used by the <=
operator. Read more
impl<T, E> Residual<T> for Result<Infallible, E>
source
impl<T, E> Residual<T> for Result<Infallible, E>
sourceimpl<T, U, E> Sum<Result<U, E>> for Result<T, E> where
T: Sum<U>,
1.16.0 · source
impl<T, U, E> Sum<Result<U, E>> for Result<T, E> where
T: Sum<U>,
1.16.0 · sourcefn sum<I>(iter: I) -> Result<T, E> where
I: Iterator<Item = Result<U, E>>,
source
fn sum<I>(iter: I) -> Result<T, E> where
I: Iterator<Item = Result<U, E>>,
sourceTakes 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));Runimpl<T, E> Try for Result<T, E>
const: unstable · source
impl<T, E> Try for Result<T, E>
const: unstable · sourcetype Residual = Result<Infallible, E>
type Residual = Result<Infallible, E>
The type of the value passed to FromResidual::from_residual
as part of ? when short-circuiting. Read more
fn from_output(output: Self::Output) -> Self
const: unstable · source
fn from_output(output: Self::Output) -> Self
const: unstable · sourceConstructs the type from its Output type. Read more
fn branch(self) -> ControlFlow<Self::Residual, Self::Output>
const: unstable · source
fn branch(self) -> ControlFlow<Self::Residual, Self::Output>
const: unstable · sourceUsed 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
impl<T: Copy, E: Copy> Copy for Result<T, E>
sourceimpl<T: Eq, E: Eq> Eq for Result<T, E>
sourceimpl<T, E> StructuralEq for Result<T, E>
sourceimpl<T, E> StructuralPartialEq for Result<T, E>
sourceAuto Trait Implementations
impl<T, E> RefUnwindSafe for Result<T, E> where
E: RefUnwindSafe,
T: RefUnwindSafe,
impl<T, E> Send for Result<T, E> where
E: Send,
T: Send,
impl<T, E> Sync for Result<T, E> where
E: Sync,
T: Sync,
impl<T, E> Unpin for Result<T, E> where
E: Unpin,
T: Unpin,
impl<T, E> UnwindSafe for Result<T, E> where
E: UnwindSafe,
T: UnwindSafe,
Blanket Implementations
impl<T> BorrowMut<T> for T where
T: ?Sized,
source
impl<T> BorrowMut<T> for T where
T: ?Sized,
sourcefn borrow_mut(&mut self) -> &mut T
const: unstable · source
fn borrow_mut(&mut self) -> &mut T
const: unstable · sourceMutably borrows from an owned value. Read more