pub enum Result<T, E> { Ok(T), Err(E),}Expand description
Result is a type that represents either success (Ok) or failure (Err).
See themodule documentation for details.
Variants§
Implementations§
Source§impl<T, E>Result<T, E>
impl<T, E>Result<T, E>
1.70.0 (const:unstable) ·Sourcepub fnis_ok_and<F>(self, f: F) ->bool
pub fnis_ok_and<F>(self, f: F) ->bool
Returnstrue if the result isOk and the value inside of it matches a predicate.
§Examples
letx:Result<u32,&str> =Ok(2);assert_eq!(x.is_ok_and(|x| x >1),true);letx:Result<u32,&str> =Ok(0);assert_eq!(x.is_ok_and(|x| x >1),false);letx:Result<u32,&str> =Err("hey");assert_eq!(x.is_ok_and(|x| x >1),false);letx:Result<String,&str> =Ok("ownership".to_string());assert_eq!(x.as_ref().is_ok_and(|x| x.len() >1),true);println!("still alive {:?}", x);1.70.0 (const:unstable) ·Sourcepub fnis_err_and<F>(self, f: F) ->bool
pub fnis_err_and<F>(self, f: F) ->bool
Returnstrue if the result isErr and the value inside of it matches a predicate.
§Examples
usestd::io::{Error, ErrorKind};letx:Result<u32, Error> =Err(Error::new(ErrorKind::NotFound,"!"));assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound),true);letx:Result<u32, Error> =Err(Error::new(ErrorKind::PermissionDenied,"!"));assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound),false);letx:Result<u32, Error> =Ok(123);assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound),false);letx:Result<u32, String> =Err("ownership".to_string());assert_eq!(x.as_ref().is_err_and(|x| x.len() >1),true);println!("still alive {:?}", x);1.0.0 (const: 1.48.0) ·Sourcepub const fnas_ref(&self) ->Result<&T,&E>
pub const fnas_ref(&self) ->Result<&T,&E>
Converts from&Result<T, E> toResult<&T, &E>.
Produces a newResult, containing a referenceinto the original, leaving the original in place.
§Examples
1.0.0 (const: 1.83.0) ·Sourcepub const fnas_mut(&mut self) ->Result<&mut T,&mut E>
pub const fnas_mut(&mut self) ->Result<&mut T,&mut E>
Converts from&mut Result<T, E> toResult<&mut T, &mut E>.
§Examples
1.0.0 (const:unstable) ·Sourcepub fnmap<U, F>(self, op: F) ->Result<U, E>where F:FnOnce(T) -> U,
pub fnmap<U, F>(self, op: F) ->Result<U, E>where F:FnOnce(T) -> U,
1.41.0 (const:unstable) ·Sourcepub fnmap_or<U, F>(self, default: U, f: F) -> Uwhere F:FnOnce(T) -> U,
pub fnmap_or<U, F>(self, default: U, f: F) -> Uwhere F:FnOnce(T) -> U,
Returns the provided default (ifErr), orapplies a function to the contained value (ifOk).
Arguments passed tomap_or are eagerly evaluated; if you are passingthe result of a function call, it is recommended to usemap_or_else,which is lazily evaluated.
§Examples
1.41.0 (const:unstable) ·Sourcepub fnmap_or_else<U, D, F>(self, default: D, f: F) -> U
pub fnmap_or_else<U, D, F>(self, default: D, f: F) -> U
Sourcepub const fnmap_or_default<U, F>(self, f: F) -> U
🔬This is a nightly-only experimental API. (result_option_map_or_default #138099)
pub const fnmap_or_default<U, F>(self, f: F) -> U
result_option_map_or_default #138099)Maps aResult<T, E> to aU by applying functionf to the containedvalue if the result isOk, otherwise ifErr, returns thedefault value for the typeU.
§Examples
1.0.0 (const:unstable) ·Sourcepub fnmap_err<F, O>(self, op: O) ->Result<T, F>where O:FnOnce(E) -> F,
pub fnmap_err<F, O>(self, op: O) ->Result<T, F>where O:FnOnce(E) -> F,
1.76.0 (const:unstable) ·Sourcepub fninspect_err<F>(self, f: F) ->Result<T, E>
pub fninspect_err<F>(self, f: F) ->Result<T, E>
1.47.0 (const:unstable) ·Sourcepub fnas_deref(&self) ->Result<&<T asDeref>::Target,&E>where T:Deref,
pub fnas_deref(&self) ->Result<&<T asDeref>::Target,&E>where T:Deref,
1.47.0 (const:unstable) ·Sourcepub fnas_deref_mut(&mut self) ->Result<&mut <T asDeref>::Target,&mut E>where T:DerefMut,
pub fnas_deref_mut(&mut self) ->Result<&mut <T asDeref>::Target,&mut E>where T:DerefMut,
Converts fromResult<T, E> (or&mut Result<T, E>) toResult<&mut <T as DerefMut>::Target, &mut E>.
Coerces theOk variant of the originalResult viaDerefMutand returns the newResult.
§Examples
letmuts ="HELLO".to_string();letmutx:Result<String, u32> =Ok("hello".to_string());lety:Result<&mutstr,&mutu32> =Ok(&muts);assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);letmuti =42;letmutx:Result<String, u32> =Err(42);lety:Result<&mutstr,&mutu32> =Err(&muti);assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);1.0.0 (const:unstable) ·Sourcepub fniter(&self) ->Iter<'_, T>ⓘ
pub fniter(&self) ->Iter<'_, T>ⓘ
Returns an iterator over the possibly contained value.
The iterator yields one value if the result isResult::Ok, otherwise none.
§Examples
1.0.0 (const:unstable) ·Sourcepub fniter_mut(&mut self) ->IterMut<'_, T>ⓘ
pub fniter_mut(&mut self) ->IterMut<'_, T>ⓘ
Returns a mutable iterator over the possibly contained value.
The iterator yields one value if the result isResult::Ok, otherwise none.
§Examples
1.4.0 ·Sourcepub fnexpect(self, msg: &str) -> Twhere E:Debug,
pub fnexpect(self, msg: &str) -> Twhere E:Debug,
Returns the containedOk value, consuming theself value.
Because this function may panic, its use is generally discouraged.Instead, prefer to use pattern matching and handle theErrcase explicitly, or callunwrap_or,unwrap_or_else, orunwrap_or_default.
§Panics
Panics if the value is anErr, with a panic message including thepassed message, and the content of theErr.
§Examples
letx:Result<u32,&str> =Err("emergency failure");x.expect("Testing expect");// panics with `Testing expect: emergency failure`§Recommended Message Style
We recommend thatexpect messages are used to describe the reason youexpect theResult should beOk.
letpath = 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 expecterror messages remember to focus on the word “should” as in “envvariable should be set by blah” or “the given binary should be availableand executable by the current user”.
For more detail on expect message styles and the reasoning behind our recommendation pleaserefer to the section on“Common MessageStyles” in thestd::error module docs.
1.0.0 ·Sourcepub fnunwrap(self) -> Twhere E:Debug,
pub fnunwrap(self) -> Twhere E:Debug,
Returns the containedOk value, consuming theself value.
Because this function may panic, its use is generally discouraged.Panics are meant for unrecoverable errors, andmay abort the entire program.
Instead, prefer to usethe? (try) operator, or pattern matchingto handle theErr case explicitly, or callunwrap_or,unwrap_or_else, orunwrap_or_default.
§Panics
Panics if the value is anErr, with a panic message provided by theErr’s value.
§Examples
Basic usage:
1.16.0 (const:unstable) ·Sourcepub fnunwrap_or_default(self) -> Twhere T:Default,
pub fnunwrap_or_default(self) -> Twhere T:Default,
Returns the containedOk value or a default
Consumes theself argument then, ifOk, returns the containedvalue, otherwise ifErr, returns the default value for thattype.
§Examples
Converts a string to an integer, turning poorly-formed stringsinto 0 (the default value for integers).parse convertsa string to any other type that implementsFromStr, returning anErr on error.
1.17.0 ·Sourcepub fnexpect_err(self, msg: &str) -> Ewhere T:Debug,
pub fnexpect_err(self, msg: &str) -> Ewhere T:Debug,
1.0.0 ·Sourcepub fnunwrap_err(self) -> Ewhere T:Debug,
pub fnunwrap_err(self) -> Ewhere T:Debug,
Sourcepub const fninto_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible #61695)
pub const fninto_ok(self) -> T
unwrap_infallible #61695)Returns the containedOk value, but never panics.
Unlikeunwrap, this method is known to never panic on theresult types it is implemented for. Therefore, it can be usedinstead ofunwrap as a maintainability safeguard that will failto compile if the error type of theResult is later changedto an error that can actually occur.
§Examples
Sourcepub const fninto_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible #61695)
pub const fninto_err(self) -> E
unwrap_infallible #61695)Returns the containedErr value, but never panics.
Unlikeunwrap_err, this method is known to never panic on theresult types it is implemented for. Therefore, it can be usedinstead ofunwrap_err as a maintainability safeguard that will failto compile if the ok type of theResult is later changedto a type that can actually occur.
§Examples
1.0.0 (const:unstable) ·Sourcepub fnand<U>(self, res:Result<U, E>) ->Result<U, E>
pub fnand<U>(self, res:Result<U, E>) ->Result<U, E>
Returnsres if the result isOk, otherwise returns theErr value ofself.
Arguments passed toand are eagerly evaluated; if you are passing theresult of a function call, it is recommended to useand_then, which islazily evaluated.
§Examples
letx:Result<u32,&str> =Ok(2);lety:Result<&str,&str> =Err("late error");assert_eq!(x.and(y),Err("late error"));letx:Result<u32,&str> =Err("early error");lety:Result<&str,&str> =Ok("foo");assert_eq!(x.and(y),Err("early error"));letx:Result<u32,&str> =Err("not a 2");lety:Result<&str,&str> =Err("late error");assert_eq!(x.and(y),Err("not a 2"));letx:Result<u32,&str> =Ok(2);lety:Result<&str,&str> =Ok("different result type");assert_eq!(x.and(y),Ok("different result type"));1.0.0 (const:unstable) ·Sourcepub fnand_then<U, F>(self, op: F) ->Result<U, E>
pub fnand_then<U, F>(self, op: F) ->Result<U, E>
Callsop if the result isOk, otherwise returns theErr value ofself.
This function can be used for control flow based onResult values.
§Examples
fnsq_then_to_string(x: u32) ->Result<String,&'staticstr> { 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 returnErr.
usestd::{io::ErrorKind, path::Path};// Note: on Windows "/" maps to "C:\"letroot_modified_time = Path::new("/").metadata().and_then(|md| md.modified());assert!(root_modified_time.is_ok());letshould_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 (const:unstable) ·Sourcepub fnor<F>(self, res:Result<T, F>) ->Result<T, F>
pub fnor<F>(self, res:Result<T, F>) ->Result<T, F>
Returnsres if the result isErr, otherwise returns theOk value ofself.
Arguments passed toor are eagerly evaluated; if you are passing theresult of a function call, it is recommended to useor_else, which islazily evaluated.
§Examples
letx:Result<u32,&str> =Ok(2);lety:Result<u32,&str> =Err("late error");assert_eq!(x.or(y),Ok(2));letx:Result<u32,&str> =Err("early error");lety:Result<u32,&str> =Ok(2);assert_eq!(x.or(y),Ok(2));letx:Result<u32,&str> =Err("not a 2");lety:Result<u32,&str> =Err("late error");assert_eq!(x.or(y),Err("late error"));letx:Result<u32,&str> =Ok(2);lety:Result<u32,&str> =Ok(100);assert_eq!(x.or(y),Ok(2));1.0.0 (const:unstable) ·Sourcepub fnor_else<F, O>(self, op: O) ->Result<T, F>
pub fnor_else<F, O>(self, op: O) ->Result<T, F>
1.0.0 (const:unstable) ·Sourcepub fnunwrap_or(self, default: T) -> T
pub fnunwrap_or(self, default: T) -> T
Returns the containedOk value or a provided default.
Arguments passed tounwrap_or are eagerly evaluated; if you are passingthe result of a function call, it is recommended to useunwrap_or_else,which is lazily evaluated.
§Examples
1.0.0 (const:unstable) ·Sourcepub fnunwrap_or_else<F>(self, op: F) -> Twhere F:FnOnce(E) -> T,
pub fnunwrap_or_else<F>(self, op: F) -> Twhere F:FnOnce(E) -> T,
1.58.0 (const:unstable) ·Sourcepub unsafe fnunwrap_unchecked(self) -> T
pub unsafe fnunwrap_unchecked(self) -> T
1.58.0 ·Sourcepub unsafe fnunwrap_err_unchecked(self) -> E
pub unsafe fnunwrap_err_unchecked(self) -> E
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>
Source§impl<T, E>Result<Option<T>, E>
impl<T, E>Result<Option<T>, E>
Source§impl<T, E>Result<Result<T, E>, E>
impl<T, E>Result<Result<T, E>, E>
1.89.0 (const: 1.89.0) ·Sourcepub const fnflatten(self) ->Result<T, E>
pub const fnflatten(self) ->Result<T, E>
Converts fromResult<Result<T, E>, E> toResult<T, E>
§Examples
letx:Result<Result<&'staticstr, u32>, u32> =Ok(Ok("hello"));assert_eq!(Ok("hello"), x.flatten());letx:Result<Result<&'staticstr, u32>, u32> =Ok(Err(6));assert_eq!(Err(6), x.flatten());letx:Result<Result<&'staticstr, u32>, u32> =Err(6);assert_eq!(Err(6), x.flatten());Flattening only removes one level of nesting at a time:
Trait Implementations§
1.0.0 ·Source§impl<A, E, V>FromIterator<Result<A, E>> forResult<V, E>where V:FromIterator<A>,
impl<A, E, V>FromIterator<Result<A, E>> forResult<V, E>where V:FromIterator<A>,
Source§fnfrom_iter<I>(iter: I) ->Result<V, E>where I:IntoIterator<Item =Result<A, E>>,
fnfrom_iter<I>(iter: I) ->Result<V, E>where I:IntoIterator<Item =Result<A, E>>,
Takes each element in theIterator: if it is anErr, no furtherelements are taken, and theErr is returned. Should noErr occur, acontainer with the values of eachResult is returned.
Here is an example which increments every integer in a vector,checking for overflow:
letv =vec![1,2];letres:Result<Vec<u32>,&'staticstr> = 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 listof integers, this time checking for underflow:
letv =vec![1,2,0];letres:Result<Vec<u32>,&'staticstr> = 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 nofurther elements are taken fromiter after the firstErr.
letv =vec![3,2,1,10];letmutshared =0;letres:Result<Vec<u32>,&'staticstr> = 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 ofshared is 6 (=3 + 2 + 1), not 16.
Source§impl<T, E, F>FromResidual<Result<Infallible, E>> forPoll<Option<Result<T, F>>>where F:From<E>,
impl<T, E, F>FromResidual<Result<Infallible, E>> forPoll<Option<Result<T, F>>>where F:From<E>,
Source§fnfrom_residual(x:Result<Infallible, E>) ->Poll<Option<Result<T, F>>>
fnfrom_residual(x:Result<Infallible, E>) ->Poll<Option<Result<T, F>>>
try_trait_v2 #84277)Residual type.Read moreSource§impl<T, E, F>FromResidual<Result<Infallible, E>> forPoll<Result<T, F>>where F:From<E>,
impl<T, E, F>FromResidual<Result<Infallible, E>> forPoll<Result<T, F>>where F:From<E>,
Source§fnfrom_residual(x:Result<Infallible, E>) ->Poll<Result<T, F>>
fnfrom_residual(x:Result<Infallible, E>) ->Poll<Result<T, F>>
try_trait_v2 #84277)Residual type.Read moreSource§impl<T, E, F>FromResidual<Result<Infallible, E>> forResult<T, F>where F:From<E>,
impl<T, E, F>FromResidual<Result<Infallible, E>> forResult<T, F>where F:From<E>,
Source§fnfrom_residual(residual:Result<Infallible, E>) ->Result<T, F>
fnfrom_residual(residual:Result<Infallible, E>) ->Result<T, F>
try_trait_v2 #84277)Residual type.Read more1.4.0 ·Source§impl<'a, T, E>IntoIterator for &'aResult<T, E>
impl<'a, T, E>IntoIterator for &'aResult<T, E>
1.4.0 ·Source§impl<'a, T, E>IntoIterator for &'a mutResult<T, E>
impl<'a, T, E>IntoIterator for &'a mutResult<T, E>
1.0.0 ·Source§impl<T, E>IntoIterator forResult<T, E>
impl<T, E>IntoIterator forResult<T, E>
1.0.0 (const:unstable) ·Source§impl<T, E>Ord forResult<T, E>
impl<T, E>Ord forResult<T, E>
1.0.0 (const:unstable) ·Source§impl<T, E>PartialOrd forResult<T, E>where T:PartialOrd, E:PartialOrd,
impl<T, E>PartialOrd forResult<T, E>where T:PartialOrd, E:PartialOrd,
1.16.0 ·Source§impl<T, U, E>Product<Result<U, E>> forResult<T, E>where T:Product<U>,
impl<T, U, E>Product<Result<U, E>> forResult<T, E>where T:Product<U>,
Source§fnproduct<I>(iter: I) ->Result<T, E>
fnproduct<I>(iter: I) ->Result<T, E>
Source§impl<T, E>Residual<T> forResult<Infallible, E>
impl<T, E>Residual<T> forResult<Infallible, E>
1.16.0 ·Source§impl<T, U, E>Sum<Result<U, E>> forResult<T, E>where T:Sum<U>,
impl<T, U, E>Sum<Result<U, E>> forResult<T, E>where T:Sum<U>,
Source§fnsum<I>(iter: I) ->Result<T, E>
fnsum<I>(iter: I) ->Result<T, E>
1.61.0 ·Source§impl<T:Termination, E:Debug>Termination forResult<T, E>
impl<T:Termination, E:Debug>Termination forResult<T, E>
Source§impl<T, E>Try forResult<T, E>
impl<T, E>Try forResult<T, E>
Source§typeOutput = T
typeOutput = T
try_trait_v2 #84277)? whennot short-circuiting.Source§typeResidual =Result<Infallible, E>
typeResidual =Result<Infallible, E>
try_trait_v2 #84277)FromResidual::from_residualas part of? when short-circuiting.Read moreSource§fnfrom_output(output: <Result<T, E> asTry>::Output) ->Result<T, E>
fnfrom_output(output: <Result<T, E> asTry>::Output) ->Result<T, E>
try_trait_v2 #84277)Output type.Read moreSource§fnbranch( self,) ->ControlFlow<<Result<T, E> asTry>::Residual, <Result<T, E> asTry>::Output>
fnbranch( self,) ->ControlFlow<<Result<T, E> asTry>::Residual, <Result<T, E> asTry>::Output>
try_trait_v2 #84277)? to decide whether the operator should produce a value(because this returnedControlFlow::Continue)or propagate a value back to the caller(because this returnedControlFlow::Break).Read more