pub enum Result<T, E> {
Ok(T),
Err(E),
}
mtls
only.Expand description
Result
is a type that represents either success (Ok
) or failure (Err
).
See the module documentation for details.
Variants§
Implementations§
source§impl<T, E> Result<T, E>
impl<T, E> Result<T, E>
1.70.0 · sourcepub fn is_ok_and(self, f: impl FnOnce(T) -> bool) -> bool
pub fn is_ok_and(self, f: impl FnOnce(T) -> bool) -> bool
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);
1.70.0 · sourcepub fn is_err_and(self, f: impl FnOnce(E) -> bool) -> bool
pub fn is_err_and(self, f: impl FnOnce(E) -> bool) -> bool
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);
1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
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
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"));
1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
pub fn as_mut(&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);
1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where
F: FnOnce(T) -> U,
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(..) => {}
}
}
1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere
F: FnOnce(T) -> U,
pub fn map_or<U, F>(self, default: U, f: F) -> Uwhere
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);
1.41.0 · sourcepub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
pub fn map_or_else<U, D, F>(self, default: D, f: F) -> 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);
1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where
O: FnOnce(E) -> F,
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
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()));
1.76.0 · sourcepub fn inspect_err<F>(self, f: F) -> Result<T, E>
pub fn inspect_err<F>(self, f: F) -> Result<T, E>
1.47.0 · sourcepub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>where
T: Deref,
pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>where
T: 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);
1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where
T: DerefMut,
pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where
T: 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);
1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T> ⓘ
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
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);
1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T> ⓘ
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
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);
1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere
E: Debug,
pub fn expect(self, msg: &str) -> Twhere
E: 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.
1.0.0 · sourcepub fn unwrap(self) -> Twhere
E: Debug,
pub fn unwrap(self) -> Twhere
E: 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 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`
1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere
T: Default,
pub fn unwrap_or_default(self) -> Twhere
T: Default,
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);
1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere
T: Debug,
pub fn expect_err(self, msg: &str) -> Ewhere
T: Debug,
1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere
T: Debug,
pub fn unwrap_err(self) -> Ewhere
T: 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");
sourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
pub fn into_ok(self) -> T
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
fn only_good_news() -> Result<String, !> {
Ok("this is fine".into())
}
let s: String = only_good_news().into_ok();
println!("{s}");
sourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
pub fn into_err(self) -> E
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
fn only_bad_news() -> Result<!, String> {
Err("Oops, it failed".into())
}
let error: String = only_bad_news().into_err();
println!("{error}");
1.0.0 · sourcepub fn and<U>(self, res: Result<U, E>) -> Result<U, E>
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
.
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"));
1.0.0 · sourcepub fn and_then<U, F>(self, op: F) -> Result<U, E>
pub fn and_then<U, F>(self, op: F) -> 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);
1.0.0 · sourcepub fn or<F>(self, res: Result<T, F>) -> Result<T, F>
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
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));
1.0.0 · sourcepub fn or_else<F, O>(self, op: O) -> Result<T, F>
pub fn or_else<F, O>(self, op: O) -> 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));
1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
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
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);
1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere
F: FnOnce(E) -> T,
pub fn unwrap_or_else<F>(self, op: F) -> Twhere
F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
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);
let x: Result<u32, &str> = Err("emergency failure");
unsafe { x.unwrap_unchecked(); } // Undefined behavior!
1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
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!
let x: Result<u32, &str> = Err("emergency failure");
assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");
source§impl<T, E> Result<&T, E>
impl<T, E> Result<&T, E>
source§impl<T, E> Result<&mut T, E>
impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where
T: Copy,
pub fn copied(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));
1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where
T: Clone,
pub fn cloned(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));
source§impl<T, E> Result<Option<T>, E>
impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
pub fn transpose(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);
source§impl<T, E> Result<Result<T, E>, E>
impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
pub fn flatten(self) -> Result<T, E>
result_flattening
)Converts from Result<Result<T, E>, E>
to Result<T, E>
§Examples
#![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§
source§impl<'de, T, E> Deserialize<'de> for Result<T, E>where
T: Deserialize<'de>,
E: Deserialize<'de>,
impl<'de, T, E> Deserialize<'de> for Result<T, E>where
T: Deserialize<'de>,
E: Deserialize<'de>,
source§fn deserialize<D>(
deserializer: D,
) -> Result<Result<T, E>, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
fn deserialize<D>(
deserializer: D,
) -> Result<Result<T, E>, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
source§impl<L, R> From<Result<R, L>> for Either<L, R>
impl<L, R> From<Result<R, L>> for Either<L, R>
Convert from Result
to Either
with Ok => Right
and Err => Left
.
source§impl<'r, T: FromData<'r> + 'r> FromData<'r> for Result<T, T::Error>
impl<'r, T: FromData<'r> + 'r> FromData<'r> for Result<T, T::Error>
source§type Error = Infallible
type Error = Infallible
source§fn from_data<'life0, 'async_trait>(
req: &'r Request<'life0>,
data: Data<'r>,
) -> Pin<Box<dyn Future<Output = Outcome<'r, Self>> + Send + 'async_trait>>where
Self: 'async_trait,
'r: 'async_trait,
'life0: 'async_trait,
fn from_data<'life0, 'async_trait>(
req: &'r Request<'life0>,
data: Data<'r>,
) -> Pin<Box<dyn Future<Output = Outcome<'r, Self>> + Send + 'async_trait>>where
Self: 'async_trait,
'r: 'async_trait,
'life0: 'async_trait,
Self
from the incoming request body data. Read more1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where
V: FromIterator<A>,
impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where
V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where
I: IntoIterator<Item = Result<A, E>>,
fn from_iter<I>(iter: I) -> Result<V, E>where
I: IntoIterator<Item = Result<A, 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.
source§impl<'a, T: FromParam<'a>> FromParam<'a> for Result<T, T::Error>
impl<'a, T: FromParam<'a>> FromParam<'a> for Result<T, T::Error>
source§type Error = Infallible
type Error = Infallible
source§impl<'r, T: FromRequest<'r>> FromRequest<'r> for Result<T, T::Error>
impl<'r, T: FromRequest<'r>> FromRequest<'r> for Result<T, T::Error>
source§type Error = Infallible
type Error = Infallible
source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Poll<Option<Result<T, F>>>where
F: From<E>,
impl<T, E, F> FromResidual<Result<Infallible, E>> for Poll<Option<Result<T, F>>>where
F: From<E>,
source§fn from_residual(x: Result<Infallible, E>) -> Poll<Option<Result<T, F>>>
fn from_residual(x: Result<Infallible, E>) -> Poll<Option<Result<T, F>>>
try_trait_v2
)Residual
type. Read moresource§impl<T, E, F> FromResidual<Result<Infallible, E>> for Poll<Result<T, F>>where
F: From<E>,
impl<T, E, F> FromResidual<Result<Infallible, E>> for Poll<Result<T, F>>where
F: From<E>,
source§fn from_residual(x: Result<Infallible, E>) -> Poll<Result<T, F>>
fn from_residual(x: Result<Infallible, E>) -> Poll<Result<T, F>>
try_trait_v2
)Residual
type. Read moresource§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where
F: From<E>,
impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where
F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
try_trait_v2
)Residual
type. Read moresource§impl<'r, T: FromSegments<'r>> FromSegments<'r> for Result<T, T::Error>
impl<'r, T: FromSegments<'r>> FromSegments<'r> for Result<T, T::Error>
§impl<A, E, T> FromUriParam<Path, A> for Result<T, E>where
T: FromUriParam<Path, A>,
impl<A, E, T> FromUriParam<Path, A> for Result<T, E>where
T: FromUriParam<Path, A>,
A no cost conversion allowing T
to be used in place of an Result<T, E>
.
§type Target = <T as FromUriParam<Path, A>>::Target
type Target = <T as FromUriParam<Path, A>>::Target
§fn from_uri_param(param: A) -> <Result<T, E> as FromUriParam<Path, A>>::Target
fn from_uri_param(param: A) -> <Result<T, E> as FromUriParam<Path, A>>::Target
T
into a value of type Self::Target
. The
resulting value of type Self::Target
will be rendered into a URI using
its UriDisplay
implementation.§impl<A, E, T> FromUriParam<Query, Option<A>> for Result<T, E>where
T: FromUriParam<Query, A>,
impl<A, E, T> FromUriParam<Query, Option<A>> for Result<T, E>where
T: FromUriParam<Query, A>,
§fn from_uri_param(
param: Option<A>,
) -> <Result<T, E> as FromUriParam<Query, Option<A>>>::Target
fn from_uri_param( param: Option<A>, ) -> <Result<T, E> as FromUriParam<Query, Option<A>>>::Target
T
into a value of type Self::Target
. The
resulting value of type Self::Target
will be rendered into a URI using
its UriDisplay
implementation.§impl<A, E, T> FromUriParam<Query, Result<A, E>> for Option<T>where
T: FromUriParam<Query, A>,
impl<A, E, T> FromUriParam<Query, Result<A, E>> for Option<T>where
T: FromUriParam<Query, A>,
§type Target = Result<<T as FromUriParam<Query, A>>::Target, E>
type Target = Result<<T as FromUriParam<Query, A>>::Target, E>
§fn from_uri_param(
param: Result<A, E>,
) -> <Option<T> as FromUriParam<Query, Result<A, E>>>::Target
fn from_uri_param( param: Result<A, E>, ) -> <Option<T> as FromUriParam<Query, Result<A, E>>>::Target
T
into a value of type Self::Target
. The
resulting value of type Self::Target
will be rendered into a URI using
its UriDisplay
implementation.§impl<A, E, T> FromUriParam<Query, Result<A, E>> for Result<T, E>where
T: FromUriParam<Query, A>,
impl<A, E, T> FromUriParam<Query, Result<A, E>> for Result<T, E>where
T: FromUriParam<Query, A>,
§type Target = Result<<T as FromUriParam<Query, A>>::Target, E>
type Target = Result<<T as FromUriParam<Query, A>>::Target, E>
§fn from_uri_param(
param: Result<A, E>,
) -> <Result<T, E> as FromUriParam<Query, Result<A, E>>>::Target
fn from_uri_param( param: Result<A, E>, ) -> <Result<T, E> as FromUriParam<Query, Result<A, E>>>::Target
T
into a value of type Self::Target
. The
resulting value of type Self::Target
will be rendered into a URI using
its UriDisplay
implementation.source§impl<L, R> Into<Result<R, L>> for Either<L, R>
impl<L, R> Into<Result<R, L>> for Either<L, R>
Convert from Either
to Result
with Right => Ok
and Left => Err
.
1.4.0 · source§impl<'a, T, E> IntoIterator for &'a Result<T, E>
impl<'a, T, E> IntoIterator for &'a Result<T, E>
1.4.0 · source§impl<'a, T, E> IntoIterator for &'a mut Result<T, E>
impl<'a, T, E> IntoIterator for &'a mut Result<T, E>
1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T> ⓘ
fn into_iter(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, []);
source§impl<S, E> IntoOutcome<Outcome<S, (Status, E), Status>> for Result<S, E>
impl<S, E> IntoOutcome<Outcome<S, (Status, E), Status>> for Result<S, E>
source§fn or_error(self, error: Status) -> Outcome<S, E>
fn or_error(self, error: Status) -> Outcome<S, E>
self
into an Outcome
. If self
represents a success, an
Outcome::Success
is returned. Otherwise, an Outcome::Error
is
returned with error
as the inner value.source§fn or_forward(self, status: Status) -> Outcome<S, E>
fn or_forward(self, status: Status) -> Outcome<S, E>
self
into an Outcome
. If self
represents a success, an
Outcome::Success
is returned. Otherwise, an Outcome::Forward
is
returned with forward
as the inner value.source§impl<'r, T: FromData<'r>> IntoOutcome<Outcome<T, (Status, <T as FromData<'r>>::Error), (Data<'r>, Status)>> for Result<T, T::Error>
impl<'r, T: FromData<'r>> IntoOutcome<Outcome<T, (Status, <T as FromData<'r>>::Error), (Data<'r>, Status)>> for Result<T, T::Error>
1.0.0 · source§impl<T, E> Ord for Result<T, E>
impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where
T: PartialOrd,
E: PartialOrd,
impl<T, E> PartialOrd for Result<T, E>where
T: PartialOrd,
E: PartialOrd,
1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where
T: Product<U>,
impl<T, U, E> Product<Result<U, E>> for Result<T, E>where
T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
fn product<I>(iter: I) -> Result<T, 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());
source§impl<T, E> Residual<T> for Result<Infallible, E>
impl<T, E> Residual<T> for Result<Infallible, E>
source§impl<'r, 'o: 'r, 't: 'o, 'e: 'o, T, E> Responder<'r, 'o> for Result<T, E>
impl<'r, 'o: 'r, 't: 'o, 'e: 'o, T, E> Responder<'r, 'o> for Result<T, E>
Responds with the wrapped Responder
in self
, whether it is Ok
or
Err
.
source§impl<T, E> Serialize for Result<T, E>
impl<T, E> Serialize for Result<T, E>
source§fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where
T: Sum<U>,
impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where
T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
fn sum<I>(iter: I) -> Result<T, 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"));
1.61.0 · source§impl<T, E> Termination for Result<T, E>where
T: Termination,
E: Debug,
impl<T, E> Termination for Result<T, E>where
T: Termination,
E: Debug,
source§impl<T, E> Try for Result<T, E>
impl<T, E> Try for Result<T, E>
source§type Output = T
type Output = T
try_trait_v2
)?
when not short-circuiting.source§type Residual = Result<Infallible, E>
type Residual = Result<Infallible, E>
try_trait_v2
)FromResidual::from_residual
as part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
try_trait_v2
)Output
type. Read moresource§fn branch(
self,
) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
fn branch( self, ) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
try_trait_v2
)?
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, E> UriDisplay<Query> for Result<T, E>where
T: UriDisplay<Query>,
impl<T, E> UriDisplay<Query> for Result<T, E>where
T: UriDisplay<Query>,
Defers to the UriDisplay<Query>
implementation for T
.
impl<T, E> Copy for Result<T, E>
impl<T, E> Eq for Result<T, E>
impl<T, U, E> FromStream<Result<T, E>> for Result<U, E>where
U: FromStream<T>,
impl<T, E> Ignorable<Query> for Result<T, E>
impl<T, E> StructuralPartialEq for Result<T, E>
Auto Trait Implementations§
impl<T, E> Freeze for Result<T, E>
impl<T, E> RefUnwindSafe for Result<T, E>where
T: RefUnwindSafe,
E: RefUnwindSafe,
impl<T, E> Send for Result<T, E>
impl<T, E> Sync for Result<T, E>
impl<T, E> Unpin for Result<T, E>
impl<T, E> UnwindSafe for Result<T, E>where
T: UnwindSafe,
E: UnwindSafe,
Blanket Implementations§
source§impl<T> AsAny for Twhere
T: Any,
impl<T> AsAny for Twhere
T: Any,
fn as_any_ref(&self) -> &(dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§unsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)source§impl<Q, K> Comparable<K> for Q
impl<Q, K> Comparable<K> for Q
source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
source§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self
with the foreground set to
value
.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red()
and
green()
, which have the same functionality but are
pithier.
§Example
Set foreground color to white using fg()
:
use yansi::{Paint, Color};
painted.fg(Color::White);
Set foreground color to white using white()
.
use yansi::Paint;
painted.white();
source§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightBlack
.
§Example
println!("{}", value.bright_black());
source§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
source§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightGreen
.
§Example
println!("{}", value.bright_green());
source§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightYellow
.
§Example
println!("{}", value.bright_yellow());
source§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
source§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightMagenta
.
§Example
println!("{}", value.bright_magenta());
source§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
source§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightWhite
.
§Example
println!("{}", value.bright_white());
source§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self
with the background set to
value
.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red()
and
on_green()
, which have the same functionality but
are pithier.
§Example
Set background color to red using fg()
:
use yansi::{Paint, Color};
painted.bg(Color::Red);
Set background color to red using on_red()
.
use yansi::Paint;
painted.on_red();
source§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
source§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightBlack
.
§Example
println!("{}", value.on_bright_black());
source§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
source§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightGreen
.
§Example
println!("{}", value.on_bright_green());
source§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightYellow
.
§Example
println!("{}", value.on_bright_yellow());
source§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightBlue
.
§Example
println!("{}", value.on_bright_blue());
source§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightMagenta
.
§Example
println!("{}", value.on_bright_magenta());
source§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightCyan
.
§Example
println!("{}", value.on_bright_cyan());
source§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightWhite
.
§Example
println!("{}", value.on_bright_white());
source§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling Attribute
value
.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold()
and
underline()
, which have the same functionality
but are pithier.
§Example
Make text bold using attr()
:
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);
Make text bold using using bold()
.
use yansi::Paint;
painted.bold();
source§fn underline(&self) -> Painted<&T>
fn underline(&self) -> Painted<&T>
Returns self
with the
attr()
set to
Attribute::Underline
.
§Example
println!("{}", value.underline());
source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Returns self
with the
attr()
set to
Attribute::RapidBlink
.
§Example
println!("{}", value.rapid_blink());
source§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi
Quirk
value
.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask()
and
wrap()
, which have the same functionality but are
pithier.
§Example
Enable wrapping using .quirk()
:
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);
Enable wrapping using wrap()
.
use yansi::Paint;
painted.wrap();
source§fn clear(&self) -> Painted<&T>
👎Deprecated since 1.0.1: renamed to resetting()
due to conflicts with Vec::clear()
.
The clear()
method will be removed in a future release.
fn clear(&self) -> Painted<&T>
resetting()
due to conflicts with Vec::clear()
.
The clear()
method will be removed in a future release.source§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the Condition
value
applies. Replaces any previous condition.
See the crate level docs for more details.
§Example
Enable styling painted
only when both stdout
and stderr
are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);