Struct serde::de::value::CowStrDeserializer
source · pub struct CowStrDeserializer<'a, E> { /* private fields */ }
Expand description
A deserializer holding a Cow<str>
.
Implementations§
Trait Implementations§
source§impl<'a, E> Clone for CowStrDeserializer<'a, E>
impl<'a, E> Clone for CowStrDeserializer<'a, E>
source§impl<'a, E> Debug for CowStrDeserializer<'a, E>
impl<'a, E> Debug for CowStrDeserializer<'a, E>
source§impl<'de, 'a, E> Deserializer<'de> for CowStrDeserializer<'a, E>where
- E: Error,
impl<'de, 'a, E> Deserializer<'de> for CowStrDeserializer<'a, E>where
- E: Error,
§type Error = E
type Error = E
source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -150,7 +150,7 @@
V: Visitor<'de>,
fn deserialize_enum<V>( @@ -150,7 +150,7 @@ V: Visitor<'de>,
Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
fn is_human_readable(&self) -> bool
Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, 'a, E> EnumAccess<'de> for CowStrDeserializer<'a, E>where
- E: Error,
impl<'de, 'a, E> EnumAccess<'de> for CowStrDeserializer<'a, E>where
- E: Error,
§type Error = E
type Error = E
§type Variant = UnitOnly<E>
type Variant = UnitOnly<E>
Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/de/value/struct.Error.html b/docs/rust/serde/de/value/struct.Error.html
index fe6d2c2b6be..5dc071dc65a 100644
--- a/docs/rust/serde/de/value/struct.Error.html
+++ b/docs/rust/serde/de/value/struct.Error.html
@@ -1,6 +1,8 @@
Error in serde::de::value - Rust pub struct Error { /* private fields */ }
Expand description
A minimal representation of all possible errors that can occur using the
IntoDeserializer
trait.
-Trait Implementations§
source§impl Error for Error
Trait Implementations§
source§impl Error for Error
source§fn description(&self) -> &str
👎Deprecated since 1.42.0: use the Display impl or to_string()1.30.0 · source§fn source(&self) -> Option<&(dyn Error + 'static)>
The lower-level source of this error, if any. Read moresource§impl Error for Error
source§fn custom<T>(msg: T) -> Selfwhere
T: Display,
Raised when there is general error when deserializing a type. Read moresource§fn invalid_type(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self
Raised when a Deserialize
receives a type different from what it was
expecting. Read moresource§fn invalid_value(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self
Raised when a Deserialize
receives a value of the right type but that
is wrong for some other reason. Read moresource§fn invalid_length(len: usize, exp: &dyn Expected) -> Self
Raised when deserializing a sequence or map and the input data contains
@@ -9,9 +11,7 @@
unrecognized name.source§fn missing_field(field: &'static str) -> Self
Raised when a Deserialize
struct type expected to receive a required
field with a particular name but that field was not present in the
input.source§fn duplicate_field(field: &'static str) -> Self
Raised when a Deserialize
struct type received more than one of the
-same field.source§impl Error for Error
source§fn description(&self) -> &str
👎Deprecated since 1.42.0: use the Display impl or to_string()1.30.0 · source§fn source(&self) -> Option<&(dyn Error + 'static)>
The lower-level source of this error, if any. Read moresource§impl PartialEq for Error
source§impl StructuralPartialEq for Error
Auto Trait Implementations§
§impl Freeze for Error
§impl RefUnwindSafe for Error
§impl Send for Error
§impl Sync for Error
§impl Unpin for Error
§impl UnwindSafe for Error
Blanket Implementations§
source§impl<T> Borrow<T> for Twhere
diff --git a/docs/rust/serde/de/value/struct.MapAccessDeserializer.html b/docs/rust/serde/de/value/struct.MapAccessDeserializer.html
index be3fe9598cd..60b77fbc868 100644
--- a/docs/rust/serde/de/value/struct.MapAccessDeserializer.html
+++ b/docs/rust/serde/de/value/struct.MapAccessDeserializer.html
@@ -1,7 +1,7 @@
MapAccessDeserializer in serde::de::value - Rust Struct serde::de::value::MapAccessDeserializer
source · pub struct MapAccessDeserializer<A> { /* private fields */ }
Expand description
A deserializer holding a MapAccess
.
Implementations§
source§impl<A> MapAccessDeserializer<A>
Trait Implementations§
source§impl<A: Clone> Clone for MapAccessDeserializer<A>
source§fn clone(&self) -> MapAccessDeserializer<A>
Returns a copy of the value. Read more1.0.0 · source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source
. Read moresource§impl<A: Debug> Debug for MapAccessDeserializer<A>
source§impl<'de, A> Deserializer<'de> for MapAccessDeserializer<A>where
- A: MapAccess<'de>,
§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
+ A: MapAccess<'de>,§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
deserialization.source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -151,7 +151,7 @@
V: Visitor<'de>,
Hint that the Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
Determine whether Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, A> EnumAccess<'de> for MapAccessDeserializer<A>where
- A: MapAccess<'de>,
§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
+ A: MapAccess<'de>,§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
deserialization.§type Variant = MapAsEnum<A>
The Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/de/value/struct.MapDeserializer.html b/docs/rust/serde/de/value/struct.MapDeserializer.html
index 15e409ed37b..21a9c282bc9 100644
--- a/docs/rust/serde/de/value/struct.MapDeserializer.html
+++ b/docs/rust/serde/de/value/struct.MapDeserializer.html
@@ -20,7 +20,7 @@
I::Item: Pair,
<I::Item as Pair>::First: IntoDeserializer<'de, E>,
<I::Item as Pair>::Second: IntoDeserializer<'de, E>,
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
@@ -193,7 +193,7 @@
I::Item: Pair,
<I::Item as Pair>::First: IntoDeserializer<'de, E>,
<I::Item as Pair>::Second: IntoDeserializer<'de, E>,
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn next_element_seed<T>(
&mut self,
seed: T,
diff --git a/docs/rust/serde/de/value/struct.SeqDeserializer.html b/docs/rust/serde/de/value/struct.SeqDeserializer.html
index a6a25343406..fbe0de66ca0 100644
--- a/docs/rust/serde/de/value/struct.SeqDeserializer.html
+++ b/docs/rust/serde/de/value/struct.SeqDeserializer.html
@@ -9,7 +9,7 @@
I: Debug,
source§impl<'de, I, T, E> Deserializer<'de> for SeqDeserializer<I, E>
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_bool<V>(
@@ -161,7 +161,7 @@
deserialize their human-readable form. Read more
source§impl<'de, I, T, E> SeqAccess<'de> for SeqDeserializer<I, E>
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn next_element_seed<V>(
&mut self,
seed: V,
diff --git a/docs/rust/serde/de/value/struct.StrDeserializer.html b/docs/rust/serde/de/value/struct.StrDeserializer.html
index 498bab01101..d14e8445657 100644
--- a/docs/rust/serde/de/value/struct.StrDeserializer.html
+++ b/docs/rust/serde/de/value/struct.StrDeserializer.html
@@ -1,6 +1,6 @@
StrDeserializer in serde::de::value - Rust Struct serde::de::value::StrDeserializer
source · pub struct StrDeserializer<'a, E> { /* private fields */ }
Expand description
A deserializer holding a &str
.
Implementations§
Trait Implementations§
source§impl<'de, E> Clone for StrDeserializer<'de, E>
source§impl<'a, E> Debug for StrDeserializer<'a, E>
source§impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -150,7 +150,7 @@
V: Visitor<'de>,
Hint that the Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
Determine whether Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, 'a, E> EnumAccess<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,§type Variant = UnitOnly<E>
The Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/ser/struct.Impossible.html b/docs/rust/serde/ser/struct.Impossible.html
index d919368937c..1e5f1d5ed51 100644
--- a/docs/rust/serde/ser/struct.Impossible.html
+++ b/docs/rust/serde/ser/struct.Impossible.html
@@ -24,35 +24,35 @@
/* other Serializer methods */
}
Trait Implementations§
source§impl<Ok, Error> SerializeMap for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error>where
+ Error: Error,
source§fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error>
Serialize a map value. Read moresource§fn serialize_entry<K, V>(
+ T: ?Sized + Serialize,
Serialize a map value. Read moresource§impl<Ok, Error> SerializeSeq for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ T: ?Sized + Serialize,
Serialize a struct field.source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
- Error: Error,
Auto Trait Implementations§
§impl<Ok, Error> Freeze for Impossible<Ok, Error>
§impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>
Serialize a struct variant field.source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
+ Error: Error,
Auto Trait Implementations§
§impl<Ok, Error> Freeze for Impossible<Ok, Error>
§impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>where
Ok: RefUnwindSafe,
Error: RefUnwindSafe,
§impl<Ok, Error> Send for Impossible<Ok, Error>where
Ok: Send,
diff --git a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
index c4943e8df79..9139d6d5e6a 100644
--- a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
+++ b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
@@ -1 +1 @@
-BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-07-31--00:35:31";
\ No newline at end of file
+BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-08-01--00:46:28";
\ No newline at end of file
diff --git a/docs/rust/type.impl/core/result/enum.Result.js b/docs/rust/type.impl/core/result/enum.Result.js
index 7f6e8ebe688..4f2e6144d9e 100644
--- a/docs/rust/type.impl/core/result/enum.Result.js
+++ b/docs/rust/type.impl/core/result/enum.Result.js
@@ -1,7 +1,7 @@
(function() {var type_impls = {
"anyhow":[["","Clone","anyhow::Result"],["source§impl<T, E> Context<T, E> for Result<T, E>
","Context","anyhow::Result"],["","Debug","anyhow::Result"],["","From<&StreamResult>","anyhow::Result"],["","From","anyhow::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","anyhow::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","anyhow::Result"],["","FromResidual>","anyhow::Result"],["","Hash","anyhow::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","anyhow::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","anyhow::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","anyhow::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","anyhow::Result"],["source§impl<T, E> Result<&T, E>
",0,"anyhow::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"anyhow::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"anyhow::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","anyhow::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","anyhow::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","anyhow::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","anyhow::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","anyhow::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","anyhow::Result"]],
"clap":[["","Clone","clap::error::Result"],["","Debug","clap::error::Result"],["","From<&StreamResult>","clap::error::Result"],["","From","clap::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap::error::Result"],["","FromResidual>","clap::error::Result"],["","Hash","clap::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap::error::Result"]],
-"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
+"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
"gimli":[["","Clone","gimli::read::Result"],["","Debug","gimli::read::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","gimli::read::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","gimli::read::Result"],["","FromResidual>","gimli::read::Result"],["","Hash","gimli::read::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","gimli::read::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","gimli::read::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","gimli::read::Result"],["source§impl<T, E> Result<&T, E>
",0,"gimli::read::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","gimli::read::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","gimli::read::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","gimli::read::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","gimli::read::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","gimli::read::Result"]],
"lzma_rs":[["","Clone","lzma_rs::error::Result"],["","Debug","lzma_rs::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","lzma_rs::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","lzma_rs::error::Result"],["","FromResidual>","lzma_rs::error::Result"],["","Hash","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","lzma_rs::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","lzma_rs::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","lzma_rs::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","lzma_rs::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","lzma_rs::error::Result"]],
"miniz_oxide":[["","Clone","miniz_oxide::MZResult"],["","Debug","miniz_oxide::MZResult"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","miniz_oxide::MZResult"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","miniz_oxide::MZResult"],["","FromResidual>","miniz_oxide::MZResult"],["","Hash","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","miniz_oxide::MZResult"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","miniz_oxide::MZResult"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","miniz_oxide::MZResult"]],
fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/de/value/struct.Error.html b/docs/rust/serde/de/value/struct.Error.html
index fe6d2c2b6be..5dc071dc65a 100644
--- a/docs/rust/serde/de/value/struct.Error.html
+++ b/docs/rust/serde/de/value/struct.Error.html
@@ -1,6 +1,8 @@
Error in serde::de::value - Rust pub struct Error { /* private fields */ }
Expand description
A minimal representation of all possible errors that can occur using the
IntoDeserializer
trait.
-Trait Implementations§
source§impl Error for Error
Trait Implementations§
source§impl Error for Error
source§fn description(&self) -> &str
👎Deprecated since 1.42.0: use the Display impl or to_string()1.30.0 · source§fn source(&self) -> Option<&(dyn Error + 'static)>
The lower-level source of this error, if any. Read moresource§impl Error for Error
source§fn custom<T>(msg: T) -> Selfwhere
T: Display,
Raised when there is general error when deserializing a type. Read moresource§fn invalid_type(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self
Raised when a Deserialize
receives a type different from what it was
expecting. Read moresource§fn invalid_value(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self
Raised when a Deserialize
receives a value of the right type but that
is wrong for some other reason. Read moresource§fn invalid_length(len: usize, exp: &dyn Expected) -> Self
Raised when deserializing a sequence or map and the input data contains
@@ -9,9 +11,7 @@
unrecognized name.source§fn missing_field(field: &'static str) -> Self
Raised when a Deserialize
struct type expected to receive a required
field with a particular name but that field was not present in the
input.source§fn duplicate_field(field: &'static str) -> Self
Raised when a Deserialize
struct type received more than one of the
-same field.source§impl Error for Error
source§fn description(&self) -> &str
👎Deprecated since 1.42.0: use the Display impl or to_string()1.30.0 · source§fn source(&self) -> Option<&(dyn Error + 'static)>
The lower-level source of this error, if any. Read moresource§impl PartialEq for Error
source§impl StructuralPartialEq for Error
Auto Trait Implementations§
§impl Freeze for Error
§impl RefUnwindSafe for Error
§impl Send for Error
§impl Sync for Error
§impl Unpin for Error
§impl UnwindSafe for Error
Blanket Implementations§
source§impl<T> Borrow<T> for Twhere
diff --git a/docs/rust/serde/de/value/struct.MapAccessDeserializer.html b/docs/rust/serde/de/value/struct.MapAccessDeserializer.html
index be3fe9598cd..60b77fbc868 100644
--- a/docs/rust/serde/de/value/struct.MapAccessDeserializer.html
+++ b/docs/rust/serde/de/value/struct.MapAccessDeserializer.html
@@ -1,7 +1,7 @@
MapAccessDeserializer in serde::de::value - Rust Struct serde::de::value::MapAccessDeserializer
source · pub struct MapAccessDeserializer<A> { /* private fields */ }
Expand description
A deserializer holding a MapAccess
.
Implementations§
source§impl<A> MapAccessDeserializer<A>
Trait Implementations§
source§impl<A: Clone> Clone for MapAccessDeserializer<A>
source§fn clone(&self) -> MapAccessDeserializer<A>
Returns a copy of the value. Read more1.0.0 · source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source
. Read moresource§impl<A: Debug> Debug for MapAccessDeserializer<A>
source§impl<'de, A> Deserializer<'de> for MapAccessDeserializer<A>where
- A: MapAccess<'de>,
§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
+ A: MapAccess<'de>,§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
deserialization.source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -151,7 +151,7 @@
V: Visitor<'de>,
Hint that the Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
Determine whether Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, A> EnumAccess<'de> for MapAccessDeserializer<A>where
- A: MapAccess<'de>,
§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
+ A: MapAccess<'de>,§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
deserialization.§type Variant = MapAsEnum<A>
The Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/de/value/struct.MapDeserializer.html b/docs/rust/serde/de/value/struct.MapDeserializer.html
index 15e409ed37b..21a9c282bc9 100644
--- a/docs/rust/serde/de/value/struct.MapDeserializer.html
+++ b/docs/rust/serde/de/value/struct.MapDeserializer.html
@@ -20,7 +20,7 @@
I::Item: Pair,
<I::Item as Pair>::First: IntoDeserializer<'de, E>,
<I::Item as Pair>::Second: IntoDeserializer<'de, E>,
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
@@ -193,7 +193,7 @@
I::Item: Pair,
<I::Item as Pair>::First: IntoDeserializer<'de, E>,
<I::Item as Pair>::Second: IntoDeserializer<'de, E>,
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn next_element_seed<T>(
&mut self,
seed: T,
diff --git a/docs/rust/serde/de/value/struct.SeqDeserializer.html b/docs/rust/serde/de/value/struct.SeqDeserializer.html
index a6a25343406..fbe0de66ca0 100644
--- a/docs/rust/serde/de/value/struct.SeqDeserializer.html
+++ b/docs/rust/serde/de/value/struct.SeqDeserializer.html
@@ -9,7 +9,7 @@
I: Debug,
source§impl<'de, I, T, E> Deserializer<'de> for SeqDeserializer<I, E>
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_bool<V>(
@@ -161,7 +161,7 @@
deserialize their human-readable form. Read more
source§impl<'de, I, T, E> SeqAccess<'de> for SeqDeserializer<I, E>
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn next_element_seed<V>(
&mut self,
seed: V,
diff --git a/docs/rust/serde/de/value/struct.StrDeserializer.html b/docs/rust/serde/de/value/struct.StrDeserializer.html
index 498bab01101..d14e8445657 100644
--- a/docs/rust/serde/de/value/struct.StrDeserializer.html
+++ b/docs/rust/serde/de/value/struct.StrDeserializer.html
@@ -1,6 +1,6 @@
StrDeserializer in serde::de::value - Rust Struct serde::de::value::StrDeserializer
source · pub struct StrDeserializer<'a, E> { /* private fields */ }
Expand description
A deserializer holding a &str
.
Implementations§
Trait Implementations§
source§impl<'de, E> Clone for StrDeserializer<'de, E>
source§impl<'a, E> Debug for StrDeserializer<'a, E>
source§impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -150,7 +150,7 @@
V: Visitor<'de>,
Hint that the Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
Determine whether Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, 'a, E> EnumAccess<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,§type Variant = UnitOnly<E>
The Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/ser/struct.Impossible.html b/docs/rust/serde/ser/struct.Impossible.html
index d919368937c..1e5f1d5ed51 100644
--- a/docs/rust/serde/ser/struct.Impossible.html
+++ b/docs/rust/serde/ser/struct.Impossible.html
@@ -24,35 +24,35 @@
/* other Serializer methods */
}
Trait Implementations§
source§impl<Ok, Error> SerializeMap for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error>where
+ Error: Error,
source§fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error>
Serialize a map value. Read moresource§fn serialize_entry<K, V>(
+ T: ?Sized + Serialize,
Serialize a map value. Read moresource§impl<Ok, Error> SerializeSeq for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ T: ?Sized + Serialize,
Serialize a struct field.source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
- Error: Error,
Auto Trait Implementations§
§impl<Ok, Error> Freeze for Impossible<Ok, Error>
§impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>
Serialize a struct variant field.source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
+ Error: Error,
Auto Trait Implementations§
§impl<Ok, Error> Freeze for Impossible<Ok, Error>
§impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>where
Ok: RefUnwindSafe,
Error: RefUnwindSafe,
§impl<Ok, Error> Send for Impossible<Ok, Error>where
Ok: Send,
diff --git a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
index c4943e8df79..9139d6d5e6a 100644
--- a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
+++ b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
@@ -1 +1 @@
-BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-07-31--00:35:31";
\ No newline at end of file
+BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-08-01--00:46:28";
\ No newline at end of file
diff --git a/docs/rust/type.impl/core/result/enum.Result.js b/docs/rust/type.impl/core/result/enum.Result.js
index 7f6e8ebe688..4f2e6144d9e 100644
--- a/docs/rust/type.impl/core/result/enum.Result.js
+++ b/docs/rust/type.impl/core/result/enum.Result.js
@@ -1,7 +1,7 @@
(function() {var type_impls = {
"anyhow":[["","Clone","anyhow::Result"],["source§impl<T, E> Context<T, E> for Result<T, E>
","Context","anyhow::Result"],["","Debug","anyhow::Result"],["","From<&StreamResult>","anyhow::Result"],["","From","anyhow::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","anyhow::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","anyhow::Result"],["","FromResidual>","anyhow::Result"],["","Hash","anyhow::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","anyhow::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","anyhow::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","anyhow::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","anyhow::Result"],["source§impl<T, E> Result<&T, E>
",0,"anyhow::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"anyhow::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"anyhow::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","anyhow::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","anyhow::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","anyhow::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","anyhow::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","anyhow::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","anyhow::Result"]],
"clap":[["","Clone","clap::error::Result"],["","Debug","clap::error::Result"],["","From<&StreamResult>","clap::error::Result"],["","From","clap::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap::error::Result"],["","FromResidual>","clap::error::Result"],["","Hash","clap::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap::error::Result"]],
-"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
+"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
"gimli":[["","Clone","gimli::read::Result"],["","Debug","gimli::read::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","gimli::read::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","gimli::read::Result"],["","FromResidual>","gimli::read::Result"],["","Hash","gimli::read::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","gimli::read::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","gimli::read::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","gimli::read::Result"],["source§impl<T, E> Result<&T, E>
",0,"gimli::read::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","gimli::read::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","gimli::read::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","gimli::read::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","gimli::read::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","gimli::read::Result"]],
"lzma_rs":[["","Clone","lzma_rs::error::Result"],["","Debug","lzma_rs::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","lzma_rs::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","lzma_rs::error::Result"],["","FromResidual>","lzma_rs::error::Result"],["","Hash","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","lzma_rs::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","lzma_rs::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","lzma_rs::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","lzma_rs::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","lzma_rs::error::Result"]],
"miniz_oxide":[["","Clone","miniz_oxide::MZResult"],["","Debug","miniz_oxide::MZResult"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","miniz_oxide::MZResult"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","miniz_oxide::MZResult"],["","FromResidual>","miniz_oxide::MZResult"],["","Hash","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","miniz_oxide::MZResult"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","miniz_oxide::MZResult"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","miniz_oxide::MZResult"]],
pub struct Error { /* private fields */ }
Expand description
A minimal representation of all possible errors that can occur using the
IntoDeserializer
trait.
Trait Implementations§
source§impl Error for Error
impl Error for Error
Trait Implementations§
source§impl Error for Error
impl Error for Error
source§fn description(&self) -> &str
fn description(&self) -> &str
1.30.0 · source§fn source(&self) -> Option<&(dyn Error + 'static)>
fn source(&self) -> Option<&(dyn Error + 'static)>
source§impl Error for Error
impl Error for Error
source§fn custom<T>(msg: T) -> Selfwhere
T: Display,
fn custom<T>(msg: T) -> Selfwhere
T: Display,
source§fn invalid_type(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self
fn invalid_type(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self
Deserialize
receives a type different from what it was
expecting. Read moresource§fn invalid_value(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self
fn invalid_value(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self
Deserialize
receives a value of the right type but that
is wrong for some other reason. Read moresource§fn invalid_length(len: usize, exp: &dyn Expected) -> Self
fn invalid_length(len: usize, exp: &dyn Expected) -> Self
source§fn missing_field(field: &'static str) -> Self
fn missing_field(field: &'static str) -> Self
Deserialize
struct type expected to receive a required
field with a particular name but that field was not present in the
input.source§fn duplicate_field(field: &'static str) -> Self
fn duplicate_field(field: &'static str) -> Self
Deserialize
struct type received more than one of the
-same field.source§impl Error for Error
impl Error for Error
source§fn description(&self) -> &str
fn description(&self) -> &str
1.30.0 · source§fn source(&self) -> Option<&(dyn Error + 'static)>
fn source(&self) -> Option<&(dyn Error + 'static)>
source§impl PartialEq for Error
impl PartialEq for Error
impl StructuralPartialEq for Error
Auto Trait Implementations§
impl Freeze for Error
impl RefUnwindSafe for Error
impl Send for Error
impl Sync for Error
impl Unpin for Error
impl UnwindSafe for Error
Blanket Implementations§
source§impl<T> Borrow<T> for Twhere
diff --git a/docs/rust/serde/de/value/struct.MapAccessDeserializer.html b/docs/rust/serde/de/value/struct.MapAccessDeserializer.html
index be3fe9598cd..60b77fbc868 100644
--- a/docs/rust/serde/de/value/struct.MapAccessDeserializer.html
+++ b/docs/rust/serde/de/value/struct.MapAccessDeserializer.html
@@ -1,7 +1,7 @@
MapAccessDeserializer in serde::de::value - Rust Struct serde::de::value::MapAccessDeserializer
source · pub struct MapAccessDeserializer<A> { /* private fields */ }
Expand description
A deserializer holding a MapAccess
.
Implementations§
source§impl<A> MapAccessDeserializer<A>
Trait Implementations§
source§impl<A: Clone> Clone for MapAccessDeserializer<A>
source§fn clone(&self) -> MapAccessDeserializer<A>
Returns a copy of the value. Read more1.0.0 · source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source
. Read moresource§impl<A: Debug> Debug for MapAccessDeserializer<A>
source§impl<'de, A> Deserializer<'de> for MapAccessDeserializer<A>where
- A: MapAccess<'de>,
§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
+ A: MapAccess<'de>,§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
deserialization.source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -151,7 +151,7 @@
V: Visitor<'de>,
Hint that the Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
Determine whether Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, A> EnumAccess<'de> for MapAccessDeserializer<A>where
- A: MapAccess<'de>,
§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
+ A: MapAccess<'de>,§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
deserialization.§type Variant = MapAsEnum<A>
The Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/de/value/struct.MapDeserializer.html b/docs/rust/serde/de/value/struct.MapDeserializer.html
index 15e409ed37b..21a9c282bc9 100644
--- a/docs/rust/serde/de/value/struct.MapDeserializer.html
+++ b/docs/rust/serde/de/value/struct.MapDeserializer.html
@@ -20,7 +20,7 @@
I::Item: Pair,
<I::Item as Pair>::First: IntoDeserializer<'de, E>,
<I::Item as Pair>::Second: IntoDeserializer<'de, E>,
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
@@ -193,7 +193,7 @@
I::Item: Pair,
<I::Item as Pair>::First: IntoDeserializer<'de, E>,
<I::Item as Pair>::Second: IntoDeserializer<'de, E>,
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn next_element_seed<T>(
&mut self,
seed: T,
diff --git a/docs/rust/serde/de/value/struct.SeqDeserializer.html b/docs/rust/serde/de/value/struct.SeqDeserializer.html
index a6a25343406..fbe0de66ca0 100644
--- a/docs/rust/serde/de/value/struct.SeqDeserializer.html
+++ b/docs/rust/serde/de/value/struct.SeqDeserializer.html
@@ -9,7 +9,7 @@
I: Debug,
source§impl<'de, I, T, E> Deserializer<'de> for SeqDeserializer<I, E>
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_bool<V>(
@@ -161,7 +161,7 @@
deserialize their human-readable form. Read more
source§impl<'de, I, T, E> SeqAccess<'de> for SeqDeserializer<I, E>
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn next_element_seed<V>(
&mut self,
seed: V,
diff --git a/docs/rust/serde/de/value/struct.StrDeserializer.html b/docs/rust/serde/de/value/struct.StrDeserializer.html
index 498bab01101..d14e8445657 100644
--- a/docs/rust/serde/de/value/struct.StrDeserializer.html
+++ b/docs/rust/serde/de/value/struct.StrDeserializer.html
@@ -1,6 +1,6 @@
StrDeserializer in serde::de::value - Rust Struct serde::de::value::StrDeserializer
source · pub struct StrDeserializer<'a, E> { /* private fields */ }
Expand description
A deserializer holding a &str
.
Implementations§
Trait Implementations§
source§impl<'de, E> Clone for StrDeserializer<'de, E>
source§impl<'a, E> Debug for StrDeserializer<'a, E>
source§impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -150,7 +150,7 @@
V: Visitor<'de>,
Hint that the Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
Determine whether Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, 'a, E> EnumAccess<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,§type Variant = UnitOnly<E>
The Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/ser/struct.Impossible.html b/docs/rust/serde/ser/struct.Impossible.html
index d919368937c..1e5f1d5ed51 100644
--- a/docs/rust/serde/ser/struct.Impossible.html
+++ b/docs/rust/serde/ser/struct.Impossible.html
@@ -24,35 +24,35 @@
/* other Serializer methods */
}
Trait Implementations§
source§impl<Ok, Error> SerializeMap for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error>where
+ Error: Error,
source§fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error>
Serialize a map value. Read moresource§fn serialize_entry<K, V>(
+ T: ?Sized + Serialize,
Serialize a map value. Read moresource§impl<Ok, Error> SerializeSeq for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ T: ?Sized + Serialize,
Serialize a struct field.source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
- Error: Error,
Auto Trait Implementations§
§impl<Ok, Error> Freeze for Impossible<Ok, Error>
§impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>
Serialize a struct variant field.source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
+ Error: Error,
Auto Trait Implementations§
§impl<Ok, Error> Freeze for Impossible<Ok, Error>
§impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>where
Ok: RefUnwindSafe,
Error: RefUnwindSafe,
§impl<Ok, Error> Send for Impossible<Ok, Error>where
Ok: Send,
diff --git a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
index c4943e8df79..9139d6d5e6a 100644
--- a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
+++ b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
@@ -1 +1 @@
-BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-07-31--00:35:31";
\ No newline at end of file
+BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-08-01--00:46:28";
\ No newline at end of file
diff --git a/docs/rust/type.impl/core/result/enum.Result.js b/docs/rust/type.impl/core/result/enum.Result.js
index 7f6e8ebe688..4f2e6144d9e 100644
--- a/docs/rust/type.impl/core/result/enum.Result.js
+++ b/docs/rust/type.impl/core/result/enum.Result.js
@@ -1,7 +1,7 @@
(function() {var type_impls = {
"anyhow":[["","Clone","anyhow::Result"],["source§impl<T, E> Context<T, E> for Result<T, E>
","Context","anyhow::Result"],["","Debug","anyhow::Result"],["","From<&StreamResult>","anyhow::Result"],["","From","anyhow::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","anyhow::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","anyhow::Result"],["","FromResidual>","anyhow::Result"],["","Hash","anyhow::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","anyhow::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","anyhow::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","anyhow::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","anyhow::Result"],["source§impl<T, E> Result<&T, E>
",0,"anyhow::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"anyhow::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"anyhow::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","anyhow::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","anyhow::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","anyhow::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","anyhow::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","anyhow::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","anyhow::Result"]],
"clap":[["","Clone","clap::error::Result"],["","Debug","clap::error::Result"],["","From<&StreamResult>","clap::error::Result"],["","From","clap::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap::error::Result"],["","FromResidual>","clap::error::Result"],["","Hash","clap::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap::error::Result"]],
-"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
+"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
"gimli":[["","Clone","gimli::read::Result"],["","Debug","gimli::read::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","gimli::read::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","gimli::read::Result"],["","FromResidual>","gimli::read::Result"],["","Hash","gimli::read::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","gimli::read::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","gimli::read::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","gimli::read::Result"],["source§impl<T, E> Result<&T, E>
",0,"gimli::read::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","gimli::read::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","gimli::read::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","gimli::read::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","gimli::read::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","gimli::read::Result"]],
"lzma_rs":[["","Clone","lzma_rs::error::Result"],["","Debug","lzma_rs::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","lzma_rs::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","lzma_rs::error::Result"],["","FromResidual>","lzma_rs::error::Result"],["","Hash","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","lzma_rs::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","lzma_rs::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","lzma_rs::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","lzma_rs::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","lzma_rs::error::Result"]],
"miniz_oxide":[["","Clone","miniz_oxide::MZResult"],["","Debug","miniz_oxide::MZResult"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","miniz_oxide::MZResult"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","miniz_oxide::MZResult"],["","FromResidual>","miniz_oxide::MZResult"],["","Hash","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","miniz_oxide::MZResult"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","miniz_oxide::MZResult"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","miniz_oxide::MZResult"]],
impl<T> Borrow<T> for Twhere
diff --git a/docs/rust/serde/de/value/struct.MapAccessDeserializer.html b/docs/rust/serde/de/value/struct.MapAccessDeserializer.html
index be3fe9598cd..60b77fbc868 100644
--- a/docs/rust/serde/de/value/struct.MapAccessDeserializer.html
+++ b/docs/rust/serde/de/value/struct.MapAccessDeserializer.html
@@ -1,7 +1,7 @@
MapAccessDeserializer in serde::de::value - Rust Struct serde::de::value::MapAccessDeserializer
source · pub struct MapAccessDeserializer<A> { /* private fields */ }
Expand description
A deserializer holding a MapAccess
.
Implementations§
source§impl<A> MapAccessDeserializer<A>
Trait Implementations§
source§impl<A: Clone> Clone for MapAccessDeserializer<A>
source§fn clone(&self) -> MapAccessDeserializer<A>
Returns a copy of the value. Read more1.0.0 · source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source
. Read moresource§impl<A: Debug> Debug for MapAccessDeserializer<A>
source§impl<'de, A> Deserializer<'de> for MapAccessDeserializer<A>where
- A: MapAccess<'de>,
§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
+ A: MapAccess<'de>,§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
deserialization.source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -151,7 +151,7 @@
V: Visitor<'de>,
Hint that the Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
Determine whether Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, A> EnumAccess<'de> for MapAccessDeserializer<A>where
- A: MapAccess<'de>,
§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
+ A: MapAccess<'de>,§type Error = <A as MapAccess<'de>>::Error
The error type that can be returned if some error occurs during
deserialization.§type Variant = MapAsEnum<A>
The Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/de/value/struct.MapDeserializer.html b/docs/rust/serde/de/value/struct.MapDeserializer.html
index 15e409ed37b..21a9c282bc9 100644
--- a/docs/rust/serde/de/value/struct.MapDeserializer.html
+++ b/docs/rust/serde/de/value/struct.MapDeserializer.html
@@ -20,7 +20,7 @@
I::Item: Pair,
<I::Item as Pair>::First: IntoDeserializer<'de, E>,
<I::Item as Pair>::Second: IntoDeserializer<'de, E>,
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
@@ -193,7 +193,7 @@
I::Item: Pair,
<I::Item as Pair>::First: IntoDeserializer<'de, E>,
<I::Item as Pair>::Second: IntoDeserializer<'de, E>,
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn next_element_seed<T>(
&mut self,
seed: T,
diff --git a/docs/rust/serde/de/value/struct.SeqDeserializer.html b/docs/rust/serde/de/value/struct.SeqDeserializer.html
index a6a25343406..fbe0de66ca0 100644
--- a/docs/rust/serde/de/value/struct.SeqDeserializer.html
+++ b/docs/rust/serde/de/value/struct.SeqDeserializer.html
@@ -9,7 +9,7 @@
I: Debug,
source§impl<'de, I, T, E> Deserializer<'de> for SeqDeserializer<I, E>
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_bool<V>(
@@ -161,7 +161,7 @@
deserialize their human-readable form. Read more
source§impl<'de, I, T, E> SeqAccess<'de> for SeqDeserializer<I, E>
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn next_element_seed<V>(
&mut self,
seed: V,
diff --git a/docs/rust/serde/de/value/struct.StrDeserializer.html b/docs/rust/serde/de/value/struct.StrDeserializer.html
index 498bab01101..d14e8445657 100644
--- a/docs/rust/serde/de/value/struct.StrDeserializer.html
+++ b/docs/rust/serde/de/value/struct.StrDeserializer.html
@@ -1,6 +1,6 @@
StrDeserializer in serde::de::value - Rust Struct serde::de::value::StrDeserializer
source · pub struct StrDeserializer<'a, E> { /* private fields */ }
Expand description
A deserializer holding a &str
.
Implementations§
Trait Implementations§
source§impl<'de, E> Clone for StrDeserializer<'de, E>
source§impl<'a, E> Debug for StrDeserializer<'a, E>
source§impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -150,7 +150,7 @@
V: Visitor<'de>,
Hint that the Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
Determine whether Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, 'a, E> EnumAccess<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,§type Variant = UnitOnly<E>
The Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/ser/struct.Impossible.html b/docs/rust/serde/ser/struct.Impossible.html
index d919368937c..1e5f1d5ed51 100644
--- a/docs/rust/serde/ser/struct.Impossible.html
+++ b/docs/rust/serde/ser/struct.Impossible.html
@@ -24,35 +24,35 @@
/* other Serializer methods */
}
Trait Implementations§
source§impl<Ok, Error> SerializeMap for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error>where
+ Error: Error,
source§fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error>
Serialize a map value. Read moresource§fn serialize_entry<K, V>(
+ T: ?Sized + Serialize,
Serialize a map value. Read moresource§impl<Ok, Error> SerializeSeq for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ T: ?Sized + Serialize,
Serialize a struct field.source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
- Error: Error,
Auto Trait Implementations§
§impl<Ok, Error> Freeze for Impossible<Ok, Error>
§impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>
Serialize a struct variant field.source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
+ Error: Error,
Auto Trait Implementations§
§impl<Ok, Error> Freeze for Impossible<Ok, Error>
§impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>where
Ok: RefUnwindSafe,
Error: RefUnwindSafe,
§impl<Ok, Error> Send for Impossible<Ok, Error>where
Ok: Send,
diff --git a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
index c4943e8df79..9139d6d5e6a 100644
--- a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
+++ b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
@@ -1 +1 @@
-BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-07-31--00:35:31";
\ No newline at end of file
+BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-08-01--00:46:28";
\ No newline at end of file
diff --git a/docs/rust/type.impl/core/result/enum.Result.js b/docs/rust/type.impl/core/result/enum.Result.js
index 7f6e8ebe688..4f2e6144d9e 100644
--- a/docs/rust/type.impl/core/result/enum.Result.js
+++ b/docs/rust/type.impl/core/result/enum.Result.js
@@ -1,7 +1,7 @@
(function() {var type_impls = {
"anyhow":[["","Clone","anyhow::Result"],["source§impl<T, E> Context<T, E> for Result<T, E>
","Context","anyhow::Result"],["","Debug","anyhow::Result"],["","From<&StreamResult>","anyhow::Result"],["","From","anyhow::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","anyhow::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","anyhow::Result"],["","FromResidual>","anyhow::Result"],["","Hash","anyhow::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","anyhow::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","anyhow::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","anyhow::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","anyhow::Result"],["source§impl<T, E> Result<&T, E>
",0,"anyhow::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"anyhow::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"anyhow::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","anyhow::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","anyhow::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","anyhow::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","anyhow::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","anyhow::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","anyhow::Result"]],
"clap":[["","Clone","clap::error::Result"],["","Debug","clap::error::Result"],["","From<&StreamResult>","clap::error::Result"],["","From","clap::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap::error::Result"],["","FromResidual>","clap::error::Result"],["","Hash","clap::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap::error::Result"]],
-"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
+"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
"gimli":[["","Clone","gimli::read::Result"],["","Debug","gimli::read::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","gimli::read::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","gimli::read::Result"],["","FromResidual>","gimli::read::Result"],["","Hash","gimli::read::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","gimli::read::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","gimli::read::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","gimli::read::Result"],["source§impl<T, E> Result<&T, E>
",0,"gimli::read::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","gimli::read::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","gimli::read::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","gimli::read::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","gimli::read::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","gimli::read::Result"]],
"lzma_rs":[["","Clone","lzma_rs::error::Result"],["","Debug","lzma_rs::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","lzma_rs::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","lzma_rs::error::Result"],["","FromResidual>","lzma_rs::error::Result"],["","Hash","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","lzma_rs::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","lzma_rs::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","lzma_rs::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","lzma_rs::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","lzma_rs::error::Result"]],
"miniz_oxide":[["","Clone","miniz_oxide::MZResult"],["","Debug","miniz_oxide::MZResult"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","miniz_oxide::MZResult"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","miniz_oxide::MZResult"],["","FromResidual>","miniz_oxide::MZResult"],["","Hash","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","miniz_oxide::MZResult"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","miniz_oxide::MZResult"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","miniz_oxide::MZResult"]],
Struct serde::de::value::MapAccessDeserializer
source · pub struct MapAccessDeserializer<A> { /* private fields */ }
Expand description
A deserializer holding a MapAccess
.
Implementations§
source§impl<A> MapAccessDeserializer<A>
impl<A> MapAccessDeserializer<A>
Trait Implementations§
source§impl<A: Clone> Clone for MapAccessDeserializer<A>
impl<A: Clone> Clone for MapAccessDeserializer<A>
source§fn clone(&self) -> MapAccessDeserializer<A>
fn clone(&self) -> MapAccessDeserializer<A>
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moresource§impl<A: Debug> Debug for MapAccessDeserializer<A>
impl<A: Debug> Debug for MapAccessDeserializer<A>
source§impl<'de, A> Deserializer<'de> for MapAccessDeserializer<A>where
- A: MapAccess<'de>,
impl<'de, A> Deserializer<'de> for MapAccessDeserializer<A>where
- A: MapAccess<'de>,
§type Error = <A as MapAccess<'de>>::Error
type Error = <A as MapAccess<'de>>::Error
§type Error = <A as MapAccess<'de>>::Error
type Error = <A as MapAccess<'de>>::Error
source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -151,7 +151,7 @@
V: Visitor<'de>,
fn deserialize_enum<V>( @@ -151,7 +151,7 @@ V: Visitor<'de>,
Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
fn is_human_readable(&self) -> bool
Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, A> EnumAccess<'de> for MapAccessDeserializer<A>where
- A: MapAccess<'de>,
impl<'de, A> EnumAccess<'de> for MapAccessDeserializer<A>where
- A: MapAccess<'de>,
§type Error = <A as MapAccess<'de>>::Error
type Error = <A as MapAccess<'de>>::Error
§type Error = <A as MapAccess<'de>>::Error
type Error = <A as MapAccess<'de>>::Error
§type Variant = MapAsEnum<A>
type Variant = MapAsEnum<A>
Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/de/value/struct.MapDeserializer.html b/docs/rust/serde/de/value/struct.MapDeserializer.html
index 15e409ed37b..21a9c282bc9 100644
--- a/docs/rust/serde/de/value/struct.MapDeserializer.html
+++ b/docs/rust/serde/de/value/struct.MapDeserializer.html
@@ -20,7 +20,7 @@
I::Item: Pair,
<I::Item as Pair>::First: IntoDeserializer<'de, E>,
<I::Item as Pair>::Second: IntoDeserializer<'de, E>,
- E: Error,
fn variant_seed<T>( self, diff --git a/docs/rust/serde/de/value/struct.MapDeserializer.html b/docs/rust/serde/de/value/struct.MapDeserializer.html index 15e409ed37b..21a9c282bc9 100644 --- a/docs/rust/serde/de/value/struct.MapDeserializer.html +++ b/docs/rust/serde/de/value/struct.MapDeserializer.html @@ -20,7 +20,7 @@ I::Item: Pair, <I::Item as Pair>::First: IntoDeserializer<'de, E>, <I::Item as Pair>::Second: IntoDeserializer<'de, E>, - E: Error,
§type Error = E
type Error = E
source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
@@ -193,7 +193,7 @@
I::Item: Pair,
<I::Item as Pair>::First: IntoDeserializer<'de, E>,
<I::Item as Pair>::Second: IntoDeserializer<'de, E>,
- E: Error,
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
@@ -193,7 +193,7 @@
I::Item: Pair,
<I::Item as Pair>::First: IntoDeserializer<'de, E>,
<I::Item as Pair>::Second: IntoDeserializer<'de, E>,
- E: Error,
§type Error = E
type Error = E
source§fn next_element_seed<T>(
&mut self,
seed: T,
diff --git a/docs/rust/serde/de/value/struct.SeqDeserializer.html b/docs/rust/serde/de/value/struct.SeqDeserializer.html
index a6a25343406..fbe0de66ca0 100644
--- a/docs/rust/serde/de/value/struct.SeqDeserializer.html
+++ b/docs/rust/serde/de/value/struct.SeqDeserializer.html
@@ -9,7 +9,7 @@
I: Debug,
fn next_element_seed<T>( &mut self, seed: T, diff --git a/docs/rust/serde/de/value/struct.SeqDeserializer.html b/docs/rust/serde/de/value/struct.SeqDeserializer.html index a6a25343406..fbe0de66ca0 100644 --- a/docs/rust/serde/de/value/struct.SeqDeserializer.html +++ b/docs/rust/serde/de/value/struct.SeqDeserializer.html @@ -9,7 +9,7 @@ I: Debug,
source§impl<'de, I, T, E> Deserializer<'de> for SeqDeserializer<I, E>
impl<'de, I, T, E> Deserializer<'de> for SeqDeserializer<I, E>
§type Error = E
type Error = E
source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_bool<V>(
@@ -161,7 +161,7 @@
deserialize their human-readable form. Read more
fn deserialize_bool<V>( @@ -161,7 +161,7 @@ deserialize their human-readable form. Read more
source§impl<'de, I, T, E> SeqAccess<'de> for SeqDeserializer<I, E>
impl<'de, I, T, E> SeqAccess<'de> for SeqDeserializer<I, E>
§type Error = E
type Error = E
source§fn next_element_seed<V>(
&mut self,
seed: V,
diff --git a/docs/rust/serde/de/value/struct.StrDeserializer.html b/docs/rust/serde/de/value/struct.StrDeserializer.html
index 498bab01101..d14e8445657 100644
--- a/docs/rust/serde/de/value/struct.StrDeserializer.html
+++ b/docs/rust/serde/de/value/struct.StrDeserializer.html
@@ -1,6 +1,6 @@
StrDeserializer in serde::de::value - Rust Struct serde::de::value::StrDeserializer
source · pub struct StrDeserializer<'a, E> { /* private fields */ }
Expand description
A deserializer holding a &str
.
Implementations§
Trait Implementations§
source§impl<'de, E> Clone for StrDeserializer<'de, E>
source§impl<'a, E> Debug for StrDeserializer<'a, E>
source§impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -150,7 +150,7 @@
V: Visitor<'de>,
Hint that the Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
Determine whether Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, 'a, E> EnumAccess<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,§type Variant = UnitOnly<E>
The Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/ser/struct.Impossible.html b/docs/rust/serde/ser/struct.Impossible.html
index d919368937c..1e5f1d5ed51 100644
--- a/docs/rust/serde/ser/struct.Impossible.html
+++ b/docs/rust/serde/ser/struct.Impossible.html
@@ -24,35 +24,35 @@
/* other Serializer methods */
}
Trait Implementations§
source§impl<Ok, Error> SerializeMap for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error>where
+ Error: Error,
source§fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error>
Serialize a map value. Read moresource§fn serialize_entry<K, V>(
+ T: ?Sized + Serialize,
Serialize a map value. Read moresource§impl<Ok, Error> SerializeSeq for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ T: ?Sized + Serialize,
Serialize a struct field.source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
- Error: Error,
Auto Trait Implementations§
§impl<Ok, Error> Freeze for Impossible<Ok, Error>
§impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>
Serialize a struct variant field.source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
+ Error: Error,
Auto Trait Implementations§
§impl<Ok, Error> Freeze for Impossible<Ok, Error>
§impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>where
Ok: RefUnwindSafe,
Error: RefUnwindSafe,
§impl<Ok, Error> Send for Impossible<Ok, Error>where
Ok: Send,
diff --git a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
index c4943e8df79..9139d6d5e6a 100644
--- a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
+++ b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
@@ -1 +1 @@
-BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-07-31--00:35:31";
\ No newline at end of file
+BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-08-01--00:46:28";
\ No newline at end of file
diff --git a/docs/rust/type.impl/core/result/enum.Result.js b/docs/rust/type.impl/core/result/enum.Result.js
index 7f6e8ebe688..4f2e6144d9e 100644
--- a/docs/rust/type.impl/core/result/enum.Result.js
+++ b/docs/rust/type.impl/core/result/enum.Result.js
@@ -1,7 +1,7 @@
(function() {var type_impls = {
"anyhow":[["","Clone","anyhow::Result"],["source§impl<T, E> Context<T, E> for Result<T, E>
","Context","anyhow::Result"],["","Debug","anyhow::Result"],["","From<&StreamResult>","anyhow::Result"],["","From","anyhow::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","anyhow::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","anyhow::Result"],["","FromResidual>","anyhow::Result"],["","Hash","anyhow::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","anyhow::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","anyhow::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","anyhow::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","anyhow::Result"],["source§impl<T, E> Result<&T, E>
",0,"anyhow::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"anyhow::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"anyhow::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","anyhow::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","anyhow::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","anyhow::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","anyhow::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","anyhow::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","anyhow::Result"]],
"clap":[["","Clone","clap::error::Result"],["","Debug","clap::error::Result"],["","From<&StreamResult>","clap::error::Result"],["","From","clap::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap::error::Result"],["","FromResidual>","clap::error::Result"],["","Hash","clap::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap::error::Result"]],
-"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
+"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
"gimli":[["","Clone","gimli::read::Result"],["","Debug","gimli::read::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","gimli::read::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","gimli::read::Result"],["","FromResidual>","gimli::read::Result"],["","Hash","gimli::read::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","gimli::read::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","gimli::read::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","gimli::read::Result"],["source§impl<T, E> Result<&T, E>
",0,"gimli::read::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","gimli::read::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","gimli::read::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","gimli::read::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","gimli::read::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","gimli::read::Result"]],
"lzma_rs":[["","Clone","lzma_rs::error::Result"],["","Debug","lzma_rs::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","lzma_rs::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","lzma_rs::error::Result"],["","FromResidual>","lzma_rs::error::Result"],["","Hash","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","lzma_rs::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","lzma_rs::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","lzma_rs::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","lzma_rs::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","lzma_rs::error::Result"]],
"miniz_oxide":[["","Clone","miniz_oxide::MZResult"],["","Debug","miniz_oxide::MZResult"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","miniz_oxide::MZResult"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","miniz_oxide::MZResult"],["","FromResidual>","miniz_oxide::MZResult"],["","Hash","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","miniz_oxide::MZResult"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","miniz_oxide::MZResult"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","miniz_oxide::MZResult"]],
fn next_element_seed<V>(
&mut self,
seed: V,
diff --git a/docs/rust/serde/de/value/struct.StrDeserializer.html b/docs/rust/serde/de/value/struct.StrDeserializer.html
index 498bab01101..d14e8445657 100644
--- a/docs/rust/serde/de/value/struct.StrDeserializer.html
+++ b/docs/rust/serde/de/value/struct.StrDeserializer.html
@@ -1,6 +1,6 @@
StrDeserializer in serde::de::value - Rust Struct serde::de::value::StrDeserializer
source · pub struct StrDeserializer<'a, E> { /* private fields */ }
Expand description
A deserializer holding a &str
.
Implementations§
Trait Implementations§
source§impl<'de, E> Clone for StrDeserializer<'de, E>
source§impl<'a, E> Debug for StrDeserializer<'a, E>
source§impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Require the Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -150,7 +150,7 @@
V: Visitor<'de>,
Hint that the Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
Determine whether Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, 'a, E> EnumAccess<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
The error type that can be returned if some error occurs during
+ E: Error,§type Variant = UnitOnly<E>
The Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/ser/struct.Impossible.html b/docs/rust/serde/ser/struct.Impossible.html
index d919368937c..1e5f1d5ed51 100644
--- a/docs/rust/serde/ser/struct.Impossible.html
+++ b/docs/rust/serde/ser/struct.Impossible.html
@@ -24,35 +24,35 @@
/* other Serializer methods */
}
Trait Implementations§
source§impl<Ok, Error> SerializeMap for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error>where
+ Error: Error,
source§fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error>
Serialize a map value. Read moresource§fn serialize_entry<K, V>(
+ T: ?Sized + Serialize,
Serialize a map value. Read moresource§impl<Ok, Error> SerializeSeq for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ T: ?Sized + Serialize,
Serialize a struct field.source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
- Error: Error,
Auto Trait Implementations§
§impl<Ok, Error> Freeze for Impossible<Ok, Error>
§impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>
Serialize a struct variant field.source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
+ Error: Error,
Auto Trait Implementations§
§impl<Ok, Error> Freeze for Impossible<Ok, Error>
§impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>where
Ok: RefUnwindSafe,
Error: RefUnwindSafe,
§impl<Ok, Error> Send for Impossible<Ok, Error>where
Ok: Send,
diff --git a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
index c4943e8df79..9139d6d5e6a 100644
--- a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
+++ b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
@@ -1 +1 @@
-BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-07-31--00:35:31";
\ No newline at end of file
+BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-08-01--00:46:28";
\ No newline at end of file
diff --git a/docs/rust/type.impl/core/result/enum.Result.js b/docs/rust/type.impl/core/result/enum.Result.js
index 7f6e8ebe688..4f2e6144d9e 100644
--- a/docs/rust/type.impl/core/result/enum.Result.js
+++ b/docs/rust/type.impl/core/result/enum.Result.js
@@ -1,7 +1,7 @@
(function() {var type_impls = {
"anyhow":[["","Clone","anyhow::Result"],["source§impl<T, E> Context<T, E> for Result<T, E>
","Context","anyhow::Result"],["","Debug","anyhow::Result"],["","From<&StreamResult>","anyhow::Result"],["","From","anyhow::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","anyhow::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","anyhow::Result"],["","FromResidual>","anyhow::Result"],["","Hash","anyhow::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","anyhow::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","anyhow::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","anyhow::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","anyhow::Result"],["source§impl<T, E> Result<&T, E>
",0,"anyhow::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"anyhow::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"anyhow::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","anyhow::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","anyhow::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","anyhow::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","anyhow::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","anyhow::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","anyhow::Result"]],
"clap":[["","Clone","clap::error::Result"],["","Debug","clap::error::Result"],["","From<&StreamResult>","clap::error::Result"],["","From","clap::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap::error::Result"],["","FromResidual>","clap::error::Result"],["","Hash","clap::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap::error::Result"]],
-"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
+"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
"gimli":[["","Clone","gimli::read::Result"],["","Debug","gimli::read::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","gimli::read::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","gimli::read::Result"],["","FromResidual>","gimli::read::Result"],["","Hash","gimli::read::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","gimli::read::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","gimli::read::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","gimli::read::Result"],["source§impl<T, E> Result<&T, E>
",0,"gimli::read::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","gimli::read::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","gimli::read::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","gimli::read::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","gimli::read::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","gimli::read::Result"]],
"lzma_rs":[["","Clone","lzma_rs::error::Result"],["","Debug","lzma_rs::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","lzma_rs::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","lzma_rs::error::Result"],["","FromResidual>","lzma_rs::error::Result"],["","Hash","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","lzma_rs::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","lzma_rs::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","lzma_rs::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","lzma_rs::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","lzma_rs::error::Result"]],
"miniz_oxide":[["","Clone","miniz_oxide::MZResult"],["","Debug","miniz_oxide::MZResult"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","miniz_oxide::MZResult"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","miniz_oxide::MZResult"],["","FromResidual>","miniz_oxide::MZResult"],["","Hash","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","miniz_oxide::MZResult"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","miniz_oxide::MZResult"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","miniz_oxide::MZResult"]],
Struct serde::de::value::StrDeserializer
source · pub struct StrDeserializer<'a, E> { /* private fields */ }
Expand description
A deserializer holding a &str
.
Implementations§
Trait Implementations§
source§impl<'de, E> Clone for StrDeserializer<'de, E>
impl<'de, E> Clone for StrDeserializer<'de, E>
source§impl<'a, E> Debug for StrDeserializer<'a, E>
impl<'a, E> Debug for StrDeserializer<'a, E>
source§impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E>where
- E: Error,
impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
type Error = E
source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>where
V: Visitor<'de>,
Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moresource§fn deserialize_enum<V>(
@@ -150,7 +150,7 @@
V: Visitor<'de>,
fn deserialize_enum<V>( @@ -150,7 +150,7 @@ V: Visitor<'de>,
Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moresource§fn is_human_readable(&self) -> bool
fn is_human_readable(&self) -> bool
Deserialize
implementations should expect to
deserialize their human-readable form. Read moresource§impl<'de, 'a, E> EnumAccess<'de> for StrDeserializer<'a, E>where
- E: Error,
impl<'de, 'a, E> EnumAccess<'de> for StrDeserializer<'a, E>where
- E: Error,
§type Error = E
type Error = E
§type Variant = UnitOnly<E>
type Variant = UnitOnly<E>
Visitor
that will be used to deserialize the content of the enum
variant.source§fn variant_seed<T>(
self,
diff --git a/docs/rust/serde/ser/struct.Impossible.html b/docs/rust/serde/ser/struct.Impossible.html
index d919368937c..1e5f1d5ed51 100644
--- a/docs/rust/serde/ser/struct.Impossible.html
+++ b/docs/rust/serde/ser/struct.Impossible.html
@@ -24,35 +24,35 @@
/* other Serializer methods */
}
fn variant_seed<T>( self, diff --git a/docs/rust/serde/ser/struct.Impossible.html b/docs/rust/serde/ser/struct.Impossible.html index d919368937c..1e5f1d5ed51 100644 --- a/docs/rust/serde/ser/struct.Impossible.html +++ b/docs/rust/serde/ser/struct.Impossible.html @@ -24,35 +24,35 @@ /* other Serializer methods */ }
Trait Implementations§
source§impl<Ok, Error> SerializeMap for Impossible<Ok, Error>where
- Error: Error,
impl<Ok, Error> SerializeMap for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error>where
+ Error: Error,
fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error>where
+ Error: Error,
source§fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error>
fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error>
source§fn serialize_entry<K, V>(
+ T: ?Sized + Serialize,
fn serialize_entry<K, V>( + T: ?Sized + Serialize,
source§impl<Ok, Error> SerializeSeq for Impossible<Ok, Error>where
- Error: Error,
impl<Ok, Error> SerializeSeq for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
- Error: Error,
impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ Error: Error,
fn serialize_field<T>( + Error: Error,
source§impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
+ Error: Error,
impl<Ok, Error> SerializeStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
- Error: Error,
impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
- Error: Error,
source§fn serialize_field<T>(
+ T: ?Sized + Serialize,
fn serialize_field<T>( + T: ?Sized + Serialize,
source§impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
+ Error: Error,
impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
- Error: Error,
impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
- Error: Error,
impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
- Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
- Error: Error,
impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
- Error: Error,
Auto Trait Implementations§
impl<Ok, Error> Freeze for Impossible<Ok, Error>
impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>
source§impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
+ Error: Error,
impl<Ok, Error> SerializeTuple for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
+ Error: Error,
impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error>where
+ Error: Error,
source§impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
+ Error: Error,
impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error>where
+ Error: Error,
Auto Trait Implementations§
impl<Ok, Error> Freeze for Impossible<Ok, Error>
impl<Ok, Error> RefUnwindSafe for Impossible<Ok, Error>where
Ok: RefUnwindSafe,
Error: RefUnwindSafe,
impl<Ok, Error> Send for Impossible<Ok, Error>where
Ok: Send,
diff --git a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
index c4943e8df79..9139d6d5e6a 100644
--- a/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
+++ b/docs/rust/shadow_build_info/constant.BUILD_TIMESTAMP.html
@@ -1 +1 @@
-BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-07-31--00:35:31";
\ No newline at end of file
+BUILD_TIMESTAMP in shadow_build_info - Rust Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-08-01--00:46:28";
\ No newline at end of file
diff --git a/docs/rust/type.impl/core/result/enum.Result.js b/docs/rust/type.impl/core/result/enum.Result.js
index 7f6e8ebe688..4f2e6144d9e 100644
--- a/docs/rust/type.impl/core/result/enum.Result.js
+++ b/docs/rust/type.impl/core/result/enum.Result.js
@@ -1,7 +1,7 @@
(function() {var type_impls = {
"anyhow":[["","Clone","anyhow::Result"],["source§impl<T, E> Context<T, E> for Result<T, E>
","Context","anyhow::Result"],["","Debug","anyhow::Result"],["","From<&StreamResult>","anyhow::Result"],["","From","anyhow::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","anyhow::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","anyhow::Result"],["","FromResidual>","anyhow::Result"],["","Hash","anyhow::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","anyhow::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","anyhow::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","anyhow::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","anyhow::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","anyhow::Result"],["source§impl<T, E> Result<&T, E>
",0,"anyhow::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"anyhow::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"anyhow::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"anyhow::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","anyhow::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","anyhow::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","anyhow::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","anyhow::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","anyhow::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","anyhow::Result"]],
"clap":[["","Clone","clap::error::Result"],["","Debug","clap::error::Result"],["","From<&StreamResult>","clap::error::Result"],["","From","clap::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap::error::Result"],["","FromResidual>","clap::error::Result"],["","Hash","clap::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap::error::Result"]],
-"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
+"clap_builder":[["","Clone","clap_builder::error::Result"],["","Debug","clap_builder::error::Result"],["","From<&StreamResult>","clap_builder::error::Result"],["","From","clap_builder::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","clap_builder::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","clap_builder::error::Result"],["","FromResidual>","clap_builder::error::Result"],["","Hash","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","clap_builder::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","clap_builder::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"clap_builder::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"clap_builder::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"clap_builder::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","clap_builder::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","clap_builder::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","clap_builder::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","clap_builder::error::Result"]],
"gimli":[["","Clone","gimli::read::Result"],["","Debug","gimli::read::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","gimli::read::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","gimli::read::Result"],["","FromResidual>","gimli::read::Result"],["","Hash","gimli::read::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","gimli::read::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","gimli::read::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","gimli::read::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","gimli::read::Result"],["source§impl<T, E> Result<&T, E>
",0,"gimli::read::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"gimli::read::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"gimli::read::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","gimli::read::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","gimli::read::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","gimli::read::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","gimli::read::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","gimli::read::Result"]],
"lzma_rs":[["","Clone","lzma_rs::error::Result"],["","Debug","lzma_rs::error::Result"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","lzma_rs::error::Result"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","lzma_rs::error::Result"],["","FromResidual>","lzma_rs::error::Result"],["","Hash","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","lzma_rs::error::Result"],["source§impl<T, E> Residual<T> for Result<Infallible, E>
","Residual","lzma_rs::error::Result"],["source§impl<T, E> Result<&T, E>
",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<&mut T, E>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
\n§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Option<T>, E>
1.33.0 (const: unstable) · sourcepub fn transpose(self) -> Option<Result<T, E>>
Transposes a Result
of an Option
into an Option
of a Result
.
\nOk(None)
will be mapped to None
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
\n§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<Result<T, E>, E>
sourcepub fn flatten(self) -> Result<T, E>
🔬This is a nightly-only experimental API. (result_flattening
)
Converts from Result<Result<T, E>, E>
to Result<T, E>
\n§Examples
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\nFlattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n",0,"lzma_rs::error::Result"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"lzma_rs::error::Result"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","lzma_rs::error::Result"],["1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
","Termination","lzma_rs::error::Result"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","lzma_rs::error::Result"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","lzma_rs::error::Result"]],
"miniz_oxide":[["","Clone","miniz_oxide::MZResult"],["","Debug","miniz_oxide::MZResult"],["1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
\nHere is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\nHere is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\nHere is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
\n\nlet v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\nSince the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
\n","FromIterator>","miniz_oxide::MZResult"],["source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
source§fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from a compatible Residual
type. Read more","FromResidual>","miniz_oxide::MZResult"],["","FromResidual>","miniz_oxide::MZResult"],["","Hash","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> IntoIterator for Result<T, E>
source§fn into_iter(self) -> IntoIter<T>
Returns a consuming iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n","IntoIterator","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Ord for Result<T, E>
1.21.0 · source§fn max(self, other: Self) -> Selfwhere\n Self: Sized,
Compares and returns the maximum of two values. Read more","Ord","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
","PartialEq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for self
and other
) and is used by the <=
\noperator. Read more","PartialOrd","miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
source§fn product<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
\n§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
\n\nlet nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n","Product>","miniz_oxide::MZResult"],["source§impl<T, E> Result<T, E>
1.70.0 · sourcepub 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.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n1.70.0 · sourcepub 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.
\n§Examples
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n1.0.0 · sourcepub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
\nConverts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n1.0.0 (const: 1.48.0) · sourcepub const fn as_ref(&self) -> Result<&T, &E>
Converts from &Result<T, E>
to Result<&T, &E>
.
\nProduces a new Result
, containing a reference\ninto the original, leaving the original in place.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n1.0.0 (const: unstable) · sourcepub fn as_mut(&mut self) -> Result<&mut T, &mut E>
Converts from &mut Result<T, E>
to Result<&mut T, &mut E>
.
\n§Examples
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
\nThis function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
\n1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n1.41.0 · sourcepub 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\na contained Err
value, or function f
to a contained Ok
value.
\nThis function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n1.0.0 · sourcepub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
\nThis function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n1.76.0 · sourcepub 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\n T: Deref,
Converts from Result<T, E>
(or &Result<T, E>
) to Result<&<T as Deref>::Target, &E>
.
\nCoerces the Ok
variant of the original Result
via Deref
\nand returns the new Result
.
\n§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
Converts from Result<T, E>
(or &mut Result<T, E>
) to Result<&mut <T as DerefMut>::Target, &mut E>
.
\nCoerces the Ok
variant of the original Result
via DerefMut
\nand returns the new Result
.
\n§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
\n§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
\n\nⓘlet path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\nHint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
\n1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
\nBecause this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
\n§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
\n§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\nⓘlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
\nConsumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
\n§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
\n\nlet good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
\n§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
\n§Examples
\nⓘlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\nsourcepub fn into_ok(self) -> T
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Ok
value, but never panics.
\nUnlike unwrap
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
\n§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\nsourcepub fn into_err(self) -> E
🔬This is a nightly-only experimental API. (unwrap_infallible
)
Returns the contained Err
value, but never panics.
\nUnlike unwrap_err
, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
\n§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n1.0.0 · sourcepub 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
.
\nArguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on Result
values.
\n§Examples
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\nOften used to chain fallible operations that may return Err
.
\n\nuse std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n1.0.0 · sourcepub 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
.
\nArguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n1.0.0 · sourcepub 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
.
\nThis function can be used for control flow based on result values.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n1.0.0 · sourcepub fn unwrap_or(self, default: T) -> T
Returns the contained Ok
value or a provided default.
\nArguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
\n§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
1.58.0 · sourcepub unsafe fn unwrap_unchecked(self) -> T
Returns the contained Ok
value, consuming the self
value,\nwithout checking that the value is not an Err
.
\n§Safety
\nCalling this method on an Err
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n1.58.0 · sourcepub unsafe fn unwrap_err_unchecked(self) -> E
Returns the contained Err
value, consuming the self
value,\nwithout checking that the value is not an Ok
.
\n§Safety
\nCalling this method on an Ok
is undefined behavior.
\n§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n",0,"miniz_oxide::MZResult"],["1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
source§fn sum<I>(iter: I) -> Result<T, E>
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
\n§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n","Sum>","miniz_oxide::MZResult"],["source§impl<T, E> Try for Result<T, E>
§type Output = T
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value produced by ?
when not short-circuiting.§type Residual = Result<Infallible, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)The type of the value passed to FromResidual::from_residual
\nas part of ?
when short-circuiting. Read moresource§fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>
🔬This is a nightly-only experimental API. (try_trait_v2
)Constructs the type from its Output
type. Read moresource§fn branch(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
🔬This is a nightly-only experimental API. (try_trait_v2
)Used in ?
to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more","Try","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Copy for Result<T, E>
","Copy","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> Eq for Result<T, E>
","Eq","miniz_oxide::MZResult"],["1.0.0 · source§impl<T, E> StructuralPartialEq for Result<T, E>
","StructuralPartialEq","miniz_oxide::MZResult"]],
Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-07-31--00:35:31";
Constant shadow_build_info::BUILD_TIMESTAMP
source · pub const BUILD_TIMESTAMP: &str = "2024-08-01--00:46:28";
source§impl<T, E> Context<T, E> for Result<T, E>
impl<T, E> Context<T, E> for Result<T, E>
1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
Here is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
Here is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
Here is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
let v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
Since the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n 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 more1.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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
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\n Self: Sized,
fn max(self, other: Self) -> Selfwhere\n Self: Sized,
1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
impl<T, E> PartialEq for Result<T, E>
1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
\noperator. Read more1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
let nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
source§impl<T, E> Residual<T> for Result<Infallible, E>
impl<T, E> Residual<T> for Result<Infallible, 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>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
pub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
pub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_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
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_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
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
Flattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
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
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_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
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
1.0.0 · sourcepub fn err(self) -> Option<E>
pub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
Converts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
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\ninto the original, leaving the original in place.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_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
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
pub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
This function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
pub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
Arguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_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\na contained Err
value, or function f
to a contained Ok
value.
This function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_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\n O: FnOnce(E) -> F,
pub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
This function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_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\n T: Deref,
pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>where\n 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
\nand returns the new Result
.
§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n 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
\nand returns the new Result
.
§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
pub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
§Examples
\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
let path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
Hint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
pub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
pub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
Consumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
let good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
pub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
§Examples
\nlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
pub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{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\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_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
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_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};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_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\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_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.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_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\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
pub fn unwrap_or_else<F>(self, op: F) -> Twhere\n 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,\nwithout checking that the value is not an Err
.
§Safety
\nCalling this method on an Err
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { 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,\nwithout checking that the value is not an Ok
.
§Safety
\nCalling this method on an Ok
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
source§impl<T, E> Try for Result<T, E>
impl<T, E> Try for Result<T, E>
§type Output = T
type Output = T
try_trait_v2
)?
when not short-circuiting.§type Residual = Result<Infallible, E>
type Residual = Result<Infallible, E>
try_trait_v2
)FromResidual::from_residual
\nas 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(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
fn branch(\n self,\n) -> 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\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read moreimpl<T, E> Copy for Result<T, E>
impl<T, E> Eq for Result<T, E>
impl<T, E> StructuralPartialEq for Result<T, E>
1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
Here is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
Here is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
Here is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
let v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
Since the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n 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 more1.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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
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\n Self: Sized,
fn max(self, other: Self) -> Selfwhere\n Self: Sized,
1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
impl<T, E> PartialEq for Result<T, E>
1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
\noperator. Read more1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
let nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
source§impl<T, E> Residual<T> for Result<Infallible, E>
impl<T, E> Residual<T> for Result<Infallible, 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>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
pub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
pub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_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
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_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
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
Flattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
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
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_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
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
1.0.0 · sourcepub fn err(self) -> Option<E>
pub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
Converts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
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\ninto the original, leaving the original in place.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_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
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
pub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
This function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
pub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
Arguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_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\na contained Err
value, or function f
to a contained Ok
value.
This function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_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\n O: FnOnce(E) -> F,
pub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
This function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_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\n T: Deref,
pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>where\n 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
\nand returns the new Result
.
§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n 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
\nand returns the new Result
.
§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
pub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
§Examples
\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
let path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
Hint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
pub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
pub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
Consumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
let good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
pub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
§Examples
\nlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
pub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{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\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_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
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_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};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_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\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_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.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_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\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
pub fn unwrap_or_else<F>(self, op: F) -> Twhere\n 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,\nwithout checking that the value is not an Err
.
§Safety
\nCalling this method on an Err
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { 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,\nwithout checking that the value is not an Ok
.
§Safety
\nCalling this method on an Ok
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
source§impl<T, E> Try for Result<T, E>
impl<T, E> Try for Result<T, E>
§type Output = T
type Output = T
try_trait_v2
)?
when not short-circuiting.§type Residual = Result<Infallible, E>
type Residual = Result<Infallible, E>
try_trait_v2
)FromResidual::from_residual
\nas 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(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
fn branch(\n self,\n) -> 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\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read moreimpl<T, E> Copy for Result<T, E>
impl<T, E> Eq for Result<T, E>
impl<T, E> StructuralPartialEq for Result<T, E>
1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
Here is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
Here is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
Here is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
let v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
Since the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n 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 more1.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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
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\n Self: Sized,
fn max(self, other: Self) -> Selfwhere\n Self: Sized,
1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
impl<T, E> PartialEq for Result<T, E>
1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
\noperator. Read more1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
let nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
source§impl<T, E> Residual<T> for Result<Infallible, E>
impl<T, E> Residual<T> for Result<Infallible, 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>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
pub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
pub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_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
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_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
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
Flattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
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
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_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
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
1.0.0 · sourcepub fn err(self) -> Option<E>
pub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
Converts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
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\ninto the original, leaving the original in place.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_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
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
pub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
This function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
pub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
Arguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_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\na contained Err
value, or function f
to a contained Ok
value.
This function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_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\n O: FnOnce(E) -> F,
pub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
This function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_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\n T: Deref,
pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>where\n 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
\nand returns the new Result
.
§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n 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
\nand returns the new Result
.
§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
pub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
§Examples
\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
let path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
Hint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
pub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
pub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
Consumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
let good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
pub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
§Examples
\nlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
pub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{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\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_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
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_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};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_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\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_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.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_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\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
pub fn unwrap_or_else<F>(self, op: F) -> Twhere\n 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,\nwithout checking that the value is not an Err
.
§Safety
\nCalling this method on an Err
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { 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,\nwithout checking that the value is not an Ok
.
§Safety
\nCalling this method on an Ok
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
source§impl<T, E> Try for Result<T, E>
impl<T, E> Try for Result<T, E>
§type Output = T
type Output = T
try_trait_v2
)?
when not short-circuiting.§type Residual = Result<Infallible, E>
type Residual = Result<Infallible, E>
try_trait_v2
)FromResidual::from_residual
\nas 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(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
fn branch(\n self,\n) -> 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\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read moreimpl<T, E> Copy for Result<T, E>
impl<T, E> Eq for Result<T, E>
impl<T, E> StructuralPartialEq for Result<T, E>
1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
Here is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
Here is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
Here is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
let v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
Since the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n 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 more1.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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
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\n Self: Sized,
fn max(self, other: Self) -> Selfwhere\n Self: Sized,
1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
impl<T, E> PartialEq for Result<T, E>
1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
\noperator. Read more1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
let nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
source§impl<T, E> Residual<T> for Result<Infallible, E>
impl<T, E> Residual<T> for Result<Infallible, 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>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
pub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
pub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_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
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_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
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
Flattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
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
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_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
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
1.0.0 · sourcepub fn err(self) -> Option<E>
pub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
Converts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
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\ninto the original, leaving the original in place.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_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
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
pub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
This function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
pub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
Arguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_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\na contained Err
value, or function f
to a contained Ok
value.
This function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_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\n O: FnOnce(E) -> F,
pub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
This function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_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\n T: Deref,
pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>where\n 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
\nand returns the new Result
.
§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n 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
\nand returns the new Result
.
§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
pub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
§Examples
\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
let path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
Hint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
pub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
pub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
Consumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
let good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
pub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
§Examples
\nlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
pub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{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\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_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
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_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};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_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\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_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.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_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\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
pub fn unwrap_or_else<F>(self, op: F) -> Twhere\n 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,\nwithout checking that the value is not an Err
.
§Safety
\nCalling this method on an Err
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { 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,\nwithout checking that the value is not an Ok
.
§Safety
\nCalling this method on an Ok
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
source§impl<T, E> Try for Result<T, E>
impl<T, E> Try for Result<T, E>
§type Output = T
type Output = T
try_trait_v2
)?
when not short-circuiting.§type Residual = Result<Infallible, E>
type Residual = Result<Infallible, E>
try_trait_v2
)FromResidual::from_residual
\nas 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(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
fn branch(\n self,\n) -> 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\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read moreimpl<T, E> Copy for Result<T, E>
impl<T, E> Eq for Result<T, E>
impl<T, E> StructuralPartialEq for Result<T, E>
1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
Here is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
Here is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
Here is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
let v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
Since the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n 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 more1.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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
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\n Self: Sized,
fn max(self, other: Self) -> Selfwhere\n Self: Sized,
1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
impl<T, E> PartialEq for Result<T, E>
1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
\noperator. Read more1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
let nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
source§impl<T, E> Residual<T> for Result<Infallible, E>
impl<T, E> Residual<T> for Result<Infallible, 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>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
pub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
pub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_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
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_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
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
Flattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
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
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_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
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
1.0.0 · sourcepub fn err(self) -> Option<E>
pub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
Converts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
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\ninto the original, leaving the original in place.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_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
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
pub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
This function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
pub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
Arguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_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\na contained Err
value, or function f
to a contained Ok
value.
This function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_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\n O: FnOnce(E) -> F,
pub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
This function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_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\n T: Deref,
pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>where\n 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
\nand returns the new Result
.
§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n 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
\nand returns the new Result
.
§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
pub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
§Examples
\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
let path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
Hint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
pub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
pub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
Consumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
let good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
pub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
§Examples
\nlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
pub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{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\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_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
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_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};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_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\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_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.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_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\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
pub fn unwrap_or_else<F>(self, op: F) -> Twhere\n 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,\nwithout checking that the value is not an Err
.
§Safety
\nCalling this method on an Err
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { 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,\nwithout checking that the value is not an Ok
.
§Safety
\nCalling this method on an Ok
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
source§impl<T, E> Try for Result<T, E>
impl<T, E> Try for Result<T, E>
§type Output = T
type Output = T
try_trait_v2
)?
when not short-circuiting.§type Residual = Result<Infallible, E>
type Residual = Result<Infallible, E>
try_trait_v2
)FromResidual::from_residual
\nas 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(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
fn branch(\n self,\n) -> 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\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read moreimpl<T, E> Copy for Result<T, E>
impl<T, E> Eq for Result<T, E>
impl<T, E> StructuralPartialEq for Result<T, E>
1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
Here is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
Here is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
Here is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
let v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
Since the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n 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 more1.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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
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\n Self: Sized,
fn max(self, other: Self) -> Selfwhere\n Self: Sized,
1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
impl<T, E> PartialEq for Result<T, E>
1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
\noperator. Read more1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
let nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
source§impl<T, E> Residual<T> for Result<Infallible, E>
impl<T, E> Residual<T> for Result<Infallible, 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>
1.59.0 · sourcepub fn copied(self) -> Result<T, E>where\n T: Copy,
pub fn copied(self) -> Result<T, E>where\n T: Copy,
Maps a Result<&mut T, E>
to a Result<T, E>
by copying the contents of the\nOk
part.
§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
1.59.0 · sourcepub fn cloned(self) -> Result<T, E>where\n T: Clone,
pub fn cloned(self) -> Result<T, E>where\n T: Clone,
Maps a Result<&mut T, E>
to a Result<T, E>
by cloning the contents of the\nOk
part.
§Examples
\nlet mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_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
.\nOk(Some(_))
and Err(_)
will be mapped to Some(Ok(_))
and Some(Err(_))
.
§Examples
\n#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_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
\n#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
Flattening only removes one level of nesting at a time:
\n\n#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
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
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_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
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
1.0.0 · sourcepub fn err(self) -> Option<E>
pub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
Converts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
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\ninto the original, leaving the original in place.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_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
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
pub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
This function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
pub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
Arguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_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\na contained Err
value, or function f
to a contained Ok
value.
This function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_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\n O: FnOnce(E) -> F,
pub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
This function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_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\n T: Deref,
pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>where\n 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
\nand returns the new Result
.
§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n 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
\nand returns the new Result
.
§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
pub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
§Examples
\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
let path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
Hint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
pub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
pub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
Consumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
let good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
pub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
§Examples
\nlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
pub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{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\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_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
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_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};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_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\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_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.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_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\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
pub fn unwrap_or_else<F>(self, op: F) -> Twhere\n 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,\nwithout checking that the value is not an Err
.
§Safety
\nCalling this method on an Err
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { 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,\nwithout checking that the value is not an Ok
.
§Safety
\nCalling this method on an Ok
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
1.61.0 · source§impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
impl<T, E> Termination for Result<T, E>where\n T: Termination,\n E: Debug,
source§impl<T, E> Try for Result<T, E>
impl<T, E> Try for Result<T, E>
§type Output = T
type Output = T
try_trait_v2
)?
when not short-circuiting.§type Residual = Result<Infallible, E>
type Residual = Result<Infallible, E>
try_trait_v2
)FromResidual::from_residual
\nas 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(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
fn branch(\n self,\n) -> 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\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read moreimpl<T, E> Copy for Result<T, E>
impl<T, E> Eq for Result<T, E>
impl<T, E> StructuralPartialEq for Result<T, E>
1.0.0 · source§impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where\n V: FromIterator<A>,
source§fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
fn from_iter<I>(iter: I) -> Result<V, E>where\n I: IntoIterator<Item = Result<A, E>>,
Takes each element in the Iterator
: if it is an Err
, no further\nelements are taken, and the Err
is returned. Should no Err
occur, a\ncontainer with the values of each Result
is returned.
Here is an example which increments every integer in a vector,\nchecking for overflow:
\n\nlet v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
Here is another example that tries to subtract one from another list\nof integers, this time checking for underflow:
\n\nlet v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
Here is a variation on the previous example, showing that no\nfurther elements are taken from iter
after the first Err
.
let v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n shared += x;\n x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
Since the third element caused an underflow, no further elements were taken,\nso the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
source§impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n F: From<E>,
impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where\n 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 more1.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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
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\n Self: Sized,
fn max(self, other: Self) -> Selfwhere\n Self: Sized,
1.0.0 · source§impl<T, E> PartialEq for Result<T, E>
impl<T, E> PartialEq for Result<T, E>
1.0.0 · source§impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
impl<T, E> PartialOrd for Result<T, E>where\n T: PartialOrd,\n E: PartialOrd,
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
\noperator. Read more1.16.0 · source§impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n T: Product<U>,
impl<T, U, E> Product<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the product of all elements is returned.
§Examples
\nThis multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err
:
let nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
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
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_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
\nuse std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
1.0.0 · sourcepub fn err(self) -> Option<E>
pub fn err(self) -> Option<E>
Converts from Result<T, E>
to Option<E>
.
Converts self
into an Option<E>
, consuming self
,\nand discarding the success value, if any.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
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\ninto the original, leaving the original in place.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_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
\nfn mutate(r: &mut Result<i32, i32>) {\n match r.as_mut() {\n Ok(v) => *v = 42,\n Err(e) => *e = 0,\n }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
1.0.0 · sourcepub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
pub fn map<U, F>(self, op: F) -> Result<U, E>where\n F: FnOnce(T) -> U,
Maps a Result<T, E>
to Result<U, E>
by applying a function to a\ncontained Ok
value, leaving an Err
value untouched.
This function can be used to compose the results of two functions.
\n§Examples
\nPrint the numbers on each line of a string multiplied by two.
\n\nlet line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n match num.parse::<i32>().map(|i| i * 2) {\n Ok(n) => println!(\"{n}\"),\n Err(..) => {}\n }\n}
1.41.0 · sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
pub fn map_or<U, F>(self, default: U, f: F) -> Uwhere\n F: FnOnce(T) -> U,
Returns the provided default (if Err
), or\napplies a function to the contained value (if Ok
).
Arguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_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\na contained Err
value, or function f
to a contained Ok
value.
This function can be used to unpack a successful result\nwhile handling an error.
\n§Examples
\nlet k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_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\n O: FnOnce(E) -> F,
pub fn map_err<F, O>(self, op: O) -> Result<T, F>where\n O: FnOnce(E) -> F,
Maps a Result<T, E>
to Result<T, F>
by applying a function to a\ncontained Err
value, leaving an Ok
value untouched.
This function can be used to pass through a successful result while handling\nan error.
\n§Examples
\nfn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_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\n T: Deref,
pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>where\n 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
\nand returns the new Result
.
§Examples
\nlet x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
1.47.0 · sourcepub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n T: DerefMut,
pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>where\n 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
\nand returns the new Result
.
§Examples
\nlet mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_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.
\nThe iterator yields one value if the result is Result::Ok
, otherwise none.
§Examples
\nlet mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n Some(v) => *v = 40,\n None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
1.4.0 · sourcepub fn expect(self, msg: &str) -> Twhere\n E: Debug,
pub fn expect(self, msg: &str) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message including the\npassed message, and the content of the Err
.
§Examples
\nlet x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
§Recommended Message Style
\nWe recommend that expect
messages are used to describe the reason you\nexpect the Result
should be Ok
.
let path = std::env::var(\"IMPORTANT_PATH\")\n .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
Hint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error
module docs.
1.0.0 · sourcepub fn unwrap(self) -> Twhere\n E: Debug,
pub fn unwrap(self) -> Twhere\n E: Debug,
Returns the contained Ok
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
§Panics
\nPanics if the value is an Err
, with a panic message provided by the\nErr
’s value.
§Examples
\nBasic usage:
\n\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
1.16.0 · sourcepub fn unwrap_or_default(self) -> Twhere\n T: Default,
pub fn unwrap_or_default(self) -> Twhere\n T: Default,
Returns the contained Ok
value or a default
Consumes the self
argument then, if Ok
, returns the contained\nvalue, otherwise if Err
, returns the default value for that\ntype.
§Examples
\nConverts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse
converts\na string to any other type that implements FromStr
, returning an\nErr
on error.
let good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
1.17.0 · sourcepub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
pub fn expect_err(self, msg: &str) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a panic message including the\npassed message, and the content of the Ok
.
§Examples
\nlet x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
1.0.0 · sourcepub fn unwrap_err(self) -> Ewhere\n T: Debug,
pub fn unwrap_err(self) -> Ewhere\n T: Debug,
Returns the contained Err
value, consuming the self
value.
§Panics
\nPanics if the value is an Ok
, with a custom panic message provided\nby the Ok
’s value.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap
as a maintainability safeguard that will fail\nto compile if the error type of the Result
is later changed\nto an error that can actually occur.
§Examples
\n\nfn only_good_news() -> Result<String, !> {\n Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{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\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err
as a maintainability safeguard that will fail\nto compile if the ok type of the Result
is later changed\nto a type that can actually occur.
§Examples
\n\nfn only_bad_news() -> Result<!, String> {\n Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{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\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_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
\nfn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_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};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_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\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_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.
\n§Examples
\nfn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_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\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
§Examples
\nlet default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
1.0.0 · sourcepub fn unwrap_or_else<F>(self, op: F) -> Twhere\n F: FnOnce(E) -> T,
pub fn unwrap_or_else<F>(self, op: F) -> Twhere\n 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,\nwithout checking that the value is not an Err
.
§Safety
\nCalling this method on an Err
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
let x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { 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,\nwithout checking that the value is not an Ok
.
§Safety
\nCalling this method on an Ok
is undefined behavior.
§Examples
\nlet x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
1.16.0 · source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n T: Sum<U>,
impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where\n 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\nelements are taken, and the Err
is returned. Should no Err
\noccur, the sum of all elements is returned.
§Examples
\nThis sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:
\n\nlet f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
source§impl<T, E> Try for Result<T, E>
impl<T, E> Try for Result<T, E>
§type Output = T
type Output = T
try_trait_v2
)?
when not short-circuiting.§type Residual = Result<Infallible, E>
type Residual = Result<Infallible, E>
try_trait_v2
)FromResidual::from_residual
\nas 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(\n self,\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>
fn branch(\n self,\n) -> 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\n(because this returned ControlFlow::Continue
)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break
). Read more