Enum Result
enum Result<T, E>
Result is a type that represents either success (Ok) or failure (Err).
See the module documentation for details.
Variants
-
Ok(T) Contains the success value
-
Err(E) Contains the error value
Implementations
impl<T, E> Result<&T, E>
const fn copied(self: Self) -> Result<T, E> where T: CopyMaps a
Result<&T, E>to aResult<T, E>by copying the contents of theOkpart.Examples
let val = 12; let x: = Ok; assert_eq!; let copied = x.copied; assert_eq!;fn cloned(self: Self) -> Result<T, E> where T: CloneMaps a
Result<&T, E>to aResult<T, E>by cloning the contents of theOkpart.Examples
let val = 12; let x: = Ok; assert_eq!; let cloned = x.cloned; assert_eq!;
impl<T, E> Result<&mut T, E>
const fn copied(self: Self) -> Result<T, E> where T: CopyMaps a
Result<&mut T, E>to aResult<T, E>by copying the contents of theOkpart.Examples
let mut val = 12; let x: = Ok; assert_eq!; let copied = x.copied; assert_eq!;fn cloned(self: Self) -> Result<T, E> where T: CloneMaps a
Result<&mut T, E>to aResult<T, E>by cloning the contents of theOkpart.Examples
let mut val = 12; let x: = Ok; assert_eq!; let cloned = x.cloned; assert_eq!;
impl<T, E> Result<Option<T>, E>
const fn transpose(self: Self) -> Option<Result<T, E>>Transposes a
Resultof anOptioninto anOptionof aResult.Ok(None)will be mapped toNone.Ok(Some(_))andErr(_)will be mapped toSome(Ok(_))andSome(Err(_)).Examples
; let x: = Ok; let y: = Some; assert_eq!;
impl<T, E> Result<Result<T, E>, E>
const fn flatten(self: Self) -> Result<T, E>Converts from
Result<Result<T, E>, E>toResult<T, E>Examples
let x: = Ok; assert_eq!; let x: = Ok; assert_eq!; let x: = Err; assert_eq!;Flattening only removes one level of nesting at a time:
let x: = Ok; assert_eq!; assert_eq!;
impl<T, E> Result<T, E>
const fn is_ok(self: &Self) -> boolReturns
trueif the result isOk.Examples
let x: = Ok; assert_eq!; let x: = Err; assert_eq!;const fn is_ok_and<F>(self: Self, f: F) -> bool where F: ~const FnOnce(T) -> bool, T: , E:Returns
trueif the result isOkand the value inside of it matches a predicate.Examples
let x: = Ok; assert_eq!; let x: = Ok; assert_eq!; let x: = Err; assert_eq!; let x: = Ok; assert_eq!; println!;const fn is_err(self: &Self) -> boolReturns
trueif the result isErr.Examples
let x: = Ok; assert_eq!; let x: = Err; assert_eq!;const fn is_err_and<F>(self: Self, f: F) -> bool where F: ~const FnOnce(E) -> bool, E: , T:Returns
trueif the result isErrand the value inside of it matches a predicate.Examples
use ; let x: = Err; assert_eq!; let x: = Err; assert_eq!; let x: = Ok; assert_eq!; let x: = Err; assert_eq!; println!;const fn ok(self: Self) -> Option<T> where T: , E:Converts from
Result<T, E>to [Option<T>].Converts
selfinto an [Option<T>], consumingself, and discarding the error, if any.Examples
let x: = Ok; assert_eq!; let x: = Err; assert_eq!;const fn err(self: Self) -> Option<E> where T: , E:Converts from
Result<T, E>to [Option<E>].Converts
selfinto an [Option<E>], consumingself, and discarding the success value, if any.Examples
let x: = Ok; assert_eq!; let x: = Err; assert_eq!;const fn as_ref(self: &Self) -> Result<&T, &E>Converts from
&Result<T, E>toResult<&T, &E>.Produces a new
Result, containing a reference into the original, leaving the original in place.Examples
let x: = Ok; assert_eq!; let x: = Err; assert_eq!;const fn as_mut(self: &mut Self) -> Result<&mut T, &mut E>Converts from
&mut Result<T, E>toResult<&mut T, &mut E>.Examples
let mut x: = Ok; mutate; assert_eq!; let mut x: = Err; mutate; assert_eq!;const fn map<U, F>(self: Self, op: F) -> Result<U, E> where F: ~const FnOnce(T) -> UMaps a
Result<T, E>toResult<U, E>by applying a function to a containedOkvalue, leaving anErrvalue 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.linesconst fn map_or<U, F>(self: Self, default: U, f: F) -> U where F: ~const FnOnce(T) -> U, T: , E: , U:Returns the provided default (if
Err), or applies a function to the contained value (ifOk).Arguments passed to
map_orare eagerly evaluated; if you are passing the result of a function call, it is recommended to usemap_or_else, which is lazily evaluated.Examples
let x: = Ok; assert_eq!; let x: = Err; assert_eq!;const fn map_or_else<U, D, F>(self: Self, default: D, f: F) -> U where D: ~const FnOnce(E) -> U, F: ~const FnOnce(T) -> UMaps a
Result<T, E>toUby applying fallback functiondefaultto a containedErrvalue, or functionfto a containedOkvalue.This function can be used to unpack a successful result while handling an error.
Examples
let k = 21; let x : = Ok; assert_eq!; let x : = Err; assert_eq!;const fn map_or_default<U, F>(self: Self, f: F) -> U where F: ~const FnOnce(T) -> U, U: ~const Default, T: , E:Maps a
Result<T, E>to aUby applying functionfto the contained value if the result isOk, otherwise ifErr, returns the default value for the typeU.Examples
let x: = Ok; let y: = Err; assert_eq!; assert_eq!;const fn map_err<F, O>(self: Self, op: O) -> Result<T, F> where O: ~const FnOnce(E) -> FMaps a
Result<T, E>toResult<T, F>by applying a function to a containedErrvalue, leaving anOkvalue untouched.This function can be used to pass through a successful result while handling an error.
Examples
let x: = Ok; assert_eq!; let x: = Err; assert_eq!;const fn inspect<F>(self: Self, f: F) -> Self where F: ~const FnOnce(&T)Calls a function with a reference to the contained value if
Ok.Returns the original result.
Examples
let x: u8 = "4" . .inspect .map .expect;const fn inspect_err<F>(self: Self, f: F) -> Self where F: ~const FnOnce(&E)Calls a function with a reference to the contained value if
Err.Returns the original result.
Examples
use ;const fn as_deref(self: &Self) -> Result<&<T as >::Target, &E> where T: ~const DerefConverts from
Result<T, E>(or&Result<T, E>) toResult<&<T as Deref>::Target, &E>.Coerces the
Okvariant of the originalResultviaDerefand returns the newResult.Examples
let x: = Ok; let y: = Ok; assert_eq!; let x: = Err; let y: = Err; assert_eq!;const fn as_deref_mut(self: &mut Self) -> Result<&mut <T as >::Target, &mut E> where T: ~const DerefMutConverts from
Result<T, E>(or&mut Result<T, E>) toResult<&mut <T as DerefMut>::Target, &mut E>.Coerces the
Okvariant of the originalResultviaDerefMutand returns the newResult.Examples
let mut s = "HELLO".to_string; let mut x: = Ok; let y: = Ok; assert_eq!; let mut i = 42; let mut x: = Err; let y: = Err; assert_eq!;const fn iter(self: &Self) -> Iter<'_, T>Returns an iterator over the possibly contained value.
The iterator yields one value if the result is
Result::Ok, otherwise none.Examples
let x: = Ok; assert_eq!; let x: = Err; assert_eq!;const fn iter_mut(self: &mut Self) -> IterMut<'_, T>Returns a mutable iterator over the possibly contained value.
The iterator yields one value if the result is
Result::Ok, otherwise none.Examples
let mut x: = Ok; match x.iter_mut.next assert_eq!; let mut x: = Err; assert_eq!;fn expect(self: Self, msg: &str) -> T where E: fmt::DebugReturns the contained
Okvalue, consuming theselfvalue.Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the
Errcase explicitly, or callunwrap_or,unwrap_or_else, orunwrap_or_default.Panics
Panics if the value is an
Err, with a panic message including the passed message, and the content of theErr.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
expectmessages are used to describe the reason you expect theResultshould beOk.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::errormodule docs.fn unwrap(self: Self) -> T where E: fmt::DebugReturns the contained
Okvalue, consuming theselfvalue.Because this function may panic, its use is generally discouraged. Panics are meant for unrecoverable errors, and may abort the entire program.
Instead, prefer to use the
?(try) operator, or pattern matching to handle theErrcase explicitly, or callunwrap_or,unwrap_or_else, orunwrap_or_default.Panics
Panics if the value is an
Err, with a panic message provided by theErr's value.Examples
Basic usage:
let x: = Ok; assert_eq!;let x: Result<u32, &str> = Err("emergency failure"); x.unwrap(); // panics with `emergency failure`const fn unwrap_or_default(self: Self) -> T where T: ~const Default, E:Returns the contained
Okvalue or a defaultConsumes the
selfargument then, ifOk, returns the contained value, otherwise ifErr, 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).
parseconverts a string to any other type that implementsFromStr, returning anErron 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!; assert_eq!;fn expect_err(self: Self, msg: &str) -> E where T: fmt::DebugReturns the contained
Errvalue, consuming theselfvalue.Panics
Panics if the value is an
Ok, with a panic message including the passed message, and the content of theOk.Examples
let x: Result<u32, &str> = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`fn unwrap_err(self: Self) -> E where T: fmt::DebugReturns the contained
Errvalue, consuming theselfvalue.Panics
Panics if the value is an
Ok, with a custom panic message provided by theOk's value.Examples
let x: Result<u32, &str> = Ok(2); x.unwrap_err(); // panics with `2`let x: = Err; assert_eq!;const fn into_ok(self: Self) -> T where E: ~const Into<never>Returns the contained
Okvalue, 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 ofunwrapas a maintainability safeguard that will fail to compile if the error type of theResultis later changed to an error that can actually occur.Examples
# # > let s: String = only_good_news.into_ok; println!;const fn into_err(self: Self) -> E where T: ~const Into<never>Returns the contained
Errvalue, 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 ofunwrap_erras a maintainability safeguard that will fail to compile if the ok type of theResultis later changed to a type that can actually occur.Examples
# # , String> let error: String = only_bad_news.into_err; println!;const fn and<U>(self: Self, res: Result<U, E>) -> Result<U, E> where T: , E: , U:Returns
resif the result isOk, otherwise returns theErrvalue ofself.Arguments passed to
andare eagerly evaluated; if you are passing the result of a function call, it is recommended to useand_then, which is lazily evaluated.Examples
let x: = Ok; let y: = Err; assert_eq!; let x: = Err; let y: = Ok; assert_eq!; let x: = Err; let y: = Err; assert_eq!; let x: = Ok; let y: = Ok; assert_eq!;const fn and_then<U, F>(self: Self, op: F) -> Result<U, E> where F: ~const FnOnce(T) -> Result<U, E>Calls
opif the result isOk, otherwise returns theErrvalue ofself.This function can be used for control flow based on
Resultvalues.Examples
assert_eq!; assert_eq!; assert_eq!;Often used to chain fallible operations that may return
Err.use ; // Note: on Windows "/" maps to "C:\" let root_modified_time = new.metadata.and_then; assert!; let should_fail = new.metadata.and_then; assert!; assert_eq!;const fn or<F>(self: Self, res: Result<T, F>) -> Result<T, F> where T: , E: , F:Returns
resif the result isErr, otherwise returns theOkvalue ofself.Arguments passed to
orare eagerly evaluated; if you are passing the result of a function call, it is recommended to useor_else, which is lazily evaluated.Examples
let x: = Ok; let y: = Err; assert_eq!; let x: = Err; let y: = Ok; assert_eq!; let x: = Err; let y: = Err; assert_eq!; let x: = Ok; let y: = Ok; assert_eq!;const fn or_else<F, O>(self: Self, op: O) -> Result<T, F> where O: ~const FnOnce(E) -> Result<T, F>Calls
opif the result isErr, otherwise returns theOkvalue ofself.This function can be used for control flow based on result values.
Examples
assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn unwrap_or(self: Self, default: T) -> T where T: , E:Returns the contained
Okvalue or a provided default.Arguments passed to
unwrap_orare eagerly evaluated; if you are passing the result of a function call, it is recommended to useunwrap_or_else, which is lazily evaluated.Examples
let default = 2; let x: = Ok; assert_eq!; let x: = Err; assert_eq!;const fn unwrap_or_else<F>(self: Self, op: F) -> T where F: ~const FnOnce(E) -> TReturns the contained
Okvalue or computes it from a closure.Examples
assert_eq!; assert_eq!;unsafe const fn unwrap_unchecked(self: Self) -> TReturns the contained
Okvalue, consuming theselfvalue, without checking that the value is not anErr.Safety
Calling this method on an
Erris undefined behavior.Examples
let x: = Ok; assert_eq!;let x: Result<u32, &str> = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior!unsafe fn unwrap_err_unchecked(self: Self) -> EReturns the contained
Errvalue, consuming theselfvalue, without checking that the value is not anOk.Safety
Calling this method on an
Okis undefined behavior.Examples
let x: Result<u32, &str> = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior!let x: = Err; assert_eq!;
impl<A, E, V: FromIterator<A>> FromIterator for Result<V, E>
fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E>Takes each element in the
Iterator: if it is anErr, no further elements are taken, and theErris returned. Should noErroccur, a container with the values of eachResultis returned.Here is an example which increments every integer in a vector, checking for overflow:
let v = vec!; let res: = v.iter.map.collect; assert_eq!;Here is another example that tries to subtract one from another list of integers, this time checking for underflow:
let v = vec!; let res: = v.iter.map.collect; assert_eq!;Here is a variation on the previous example, showing that no further elements are taken from
iterafter the firstErr.let v = vec!; let mut shared = 0; let res: = v.iter.map.collect; assert_eq!; assert_eq!;Since the third element caused an underflow, no further elements were taken, so the final value of
sharedis 6 (=3 + 2 + 1), not 16.
impl<T> Any for Result<T, E>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Result<T, E>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Result<T, E>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for Result<T, E>
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for Result<T, E>
fn from(t: T) -> TReturns the argument unchanged.
impl<T, E> Clone for Result<T, E>
fn clone(self: &Self) -> Selffn clone_from(self: &mut Self, source: &Self)
impl<T, E> Freeze for Result<T, E>
impl<T, E> IntoIterator for Result<T, E>
fn into_iter(self: Self) -> IntoIter<T>Returns a consuming iterator over the possibly contained value.
The iterator yields one value if the result is
Result::Ok, otherwise none.Examples
let x: = Ok; let v: = x.into_iter.collect; assert_eq!; let x: = Err; let v: = x.into_iter.collect; assert_eq!;
impl<T, E> RefUnwindSafe for Result<T, E>
impl<T, E> Residual for Result<convert::Infallible, E>
impl<T, E> Send for Result<T, E>
impl<T, E> StructuralPartialEq for Result<T, E>
impl<T, E> Sync for Result<T, E>
impl<T, E> Try for Result<T, E>
fn from_output(output: <Self as >::Output) -> Selffn branch(self: Self) -> ControlFlow<<Self as >::Residual, <Self as >::Output>
impl<T, E> Unpin for Result<T, E>
impl<T, E> UnwindSafe for Result<T, E>
impl<T, E> UseCloned for Result<T, E>
impl<T, E, F: ~const From<E>> FromResidual for Result<T, F>
fn from_residual(residual: Result<convert::Infallible, E>) -> Self
impl<T, E, F: ~const From<E>> FromResidual for Result<T, F>
fn from_residual(ops::Yeet: ops::Yeet<E>) -> Self
impl<T, U> Into for Result<T, E>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Result<T, E>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Result<T, E>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>
impl<T, U, E> Product for Result<T, E>
fn product<I>(iter: I) -> Result<T, E> where I: Iterator<Item = Result<U, E>>Takes each element in the [
Iterator]: if it is anErr, no further elements are taken, and theErris returned. Should noErroccur, 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!; let total: = nums.iter.map.product; assert_eq!; let nums = vec!; let total: = nums.iter.map.product; assert!;
impl<T, U, E> Sum for Result<T, E>
fn sum<I>(iter: I) -> Result<T, E> where I: Iterator<Item = Result<U, E>>Takes each element in the [
Iterator]: if it is anErr, no further elements are taken, and theErris returned. Should noErroccur, 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 = ; let v = vec!; let res: = v.iter.map.sum; assert_eq!; let v = vec!; let res: = v.iter.map.sum; assert_eq!;
impl<T: $crate::fmt::Debug, E: $crate::fmt::Debug> Debug for Result<T, E>
fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<'_>) -> $crate::fmt::Result
impl<T: $crate::hash::Hash, E: $crate::hash::Hash> Hash for Result<T, E>
fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H)
impl<T: $crate::marker::Copy, E: $crate::marker::Copy> Copy for Result<T, E>
impl<T: CloneFromCell, E: CloneFromCell> CloneFromCell for Result<T, E>
impl<T: ~const $crate::cmp::Eq, E: ~const $crate::cmp::Eq> Eq for Result<T, E>
impl<T: ~const $crate::cmp::Ord, E: ~const $crate::cmp::Ord> Ord for Result<T, E>
fn cmp(self: &Self, other: &Result<T, E>) -> $crate::cmp::Ordering
impl<T: ~const $crate::cmp::PartialEq, E: ~const $crate::cmp::PartialEq> PartialEq for Result<T, E>
fn eq(self: &Self, other: &Result<T, E>) -> bool
impl<T: ~const $crate::cmp::PartialOrd, E: ~const $crate::cmp::PartialOrd> PartialOrd for Result<T, E>
fn partial_cmp(self: &Self, other: &Result<T, E>) -> $crate::option::Option<$crate::cmp::Ordering>