Movatterモバイル変換


[0]ホーム

URL:


Result

std::result

EnumResult 

1.0.0 ·Source
pub enum Result<T, E> {    Ok(T),    Err(E),}
Expand description

Result is a type that represents either success (Ok) or failure (Err).

See themodule documentation for details.

Variants§

§1.0.0

Ok(T)

Contains the success value

§1.0.0

Err(E)

Contains the error value

Implementations§

Source§

impl<T, E>Result<T, E>

1.0.0 (const: 1.48.0) ·Source

pub const fnis_ok(&self) ->bool

Returnstrue if the result isOk.

§Examples
letx:Result<i32,&str> =Ok(-3);assert_eq!(x.is_ok(),true);letx:Result<i32,&str> =Err("Some error message");assert_eq!(x.is_ok(),false);
1.70.0 (const:unstable) ·Source

pub fnis_ok_and<F>(self, f: F) ->bool
where F:FnOnce(T) ->bool,

Returnstrue if the result isOk and the value inside of it matches a predicate.

§Examples
letx:Result<u32,&str> =Ok(2);assert_eq!(x.is_ok_and(|x| x >1),true);letx:Result<u32,&str> =Ok(0);assert_eq!(x.is_ok_and(|x| x >1),false);letx:Result<u32,&str> =Err("hey");assert_eq!(x.is_ok_and(|x| x >1),false);letx:Result<String,&str> =Ok("ownership".to_string());assert_eq!(x.as_ref().is_ok_and(|x| x.len() >1),true);println!("still alive {:?}", x);
1.0.0 (const: 1.48.0) ·Source

pub const fnis_err(&self) ->bool

Returnstrue if the result isErr.

§Examples
letx:Result<i32,&str> =Ok(-3);assert_eq!(x.is_err(),false);letx:Result<i32,&str> =Err("Some error message");assert_eq!(x.is_err(),true);
1.70.0 (const:unstable) ·Source

pub fnis_err_and<F>(self, f: F) ->bool
where F:FnOnce(E) ->bool,

Returnstrue if the result isErr and the value inside of it matches a predicate.

§Examples
usestd::io::{Error, ErrorKind};letx:Result<u32, Error> =Err(Error::new(ErrorKind::NotFound,"!"));assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound),true);letx:Result<u32, Error> =Err(Error::new(ErrorKind::PermissionDenied,"!"));assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound),false);letx:Result<u32, Error> =Ok(123);assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound),false);letx:Result<u32, String> =Err("ownership".to_string());assert_eq!(x.as_ref().is_err_and(|x| x.len() >1),true);println!("still alive {:?}", x);
1.0.0 (const:unstable) ·Source

pub fnok(self) ->Option<T>

Converts fromResult<T, E> toOption<T>.

Convertsself into anOption<T>, consumingself,and discarding the error, if any.

§Examples
letx:Result<u32,&str> =Ok(2);assert_eq!(x.ok(),Some(2));letx:Result<u32,&str> =Err("Nothing here");assert_eq!(x.ok(),None);
1.0.0 (const:unstable) ·Source

pub fnerr(self) ->Option<E>

Converts fromResult<T, E> toOption<E>.

Convertsself into anOption<E>, consumingself,and discarding the success value, if any.

§Examples
letx:Result<u32,&str> =Ok(2);assert_eq!(x.err(),None);letx:Result<u32,&str> =Err("Nothing here");assert_eq!(x.err(),Some("Nothing here"));
1.0.0 (const: 1.48.0) ·Source

pub const fnas_ref(&self) ->Result<&T,&E>

Converts from&Result<T, E> toResult<&T, &E>.

Produces a newResult, containing a referenceinto the original, leaving the original in place.

§Examples
letx:Result<u32,&str> =Ok(2);assert_eq!(x.as_ref(),Ok(&2));letx:Result<u32,&str> =Err("Error");assert_eq!(x.as_ref(),Err(&"Error"));
1.0.0 (const: 1.83.0) ·Source

pub const fnas_mut(&mut self) ->Result<&mut T,&mut E>

Converts from&mut Result<T, E> toResult<&mut T, &mut E>.

§Examples
fnmutate(r:&mutResult<i32, i32>) {matchr.as_mut() {Ok(v) =>*v =42,Err(e) =>*e =0,    }}letmutx:Result<i32, i32> =Ok(2);mutate(&mutx);assert_eq!(x.unwrap(),42);letmutx:Result<i32, i32> =Err(13);mutate(&mutx);assert_eq!(x.unwrap_err(),0);
1.0.0 (const:unstable) ·Source

pub fnmap<U, F>(self, op: F) ->Result<U, E>
where F:FnOnce(T) -> U,

Maps aResult<T, E> toResult<U, E> by applying a function to acontainedOk value, leaving anErr value untouched.

This function can be used to compose the results of two functions.

§Examples

Print the numbers on each line of a string multiplied by two.

letline ="1\n2\n3\n4\n";fornuminline.lines() {matchnum.parse::<i32>().map(|i| i *2) {Ok(n) =>println!("{n}"),Err(..) => {}    }}
1.41.0 (const:unstable) ·Source

pub fnmap_or<U, F>(self, default: U, f: F) -> U
where F:FnOnce(T) -> U,

Returns the provided default (ifErr), orapplies a function to the contained value (ifOk).

Arguments passed tomap_or are eagerly evaluated; if you are passingthe result of a function call, it is recommended to usemap_or_else,which is lazily evaluated.

§Examples
letx:Result<_,&str> =Ok("foo");assert_eq!(x.map_or(42, |v| v.len()),3);letx:Result<&str,_> =Err("bar");assert_eq!(x.map_or(42, |v| v.len()),42);
1.41.0 (const:unstable) ·Source

pub fnmap_or_else<U, D, F>(self, default: D, f: F) -> U
where D:FnOnce(E) -> U, F:FnOnce(T) -> U,

Maps aResult<T, E> toU by applying fallback functiondefault toa containedErr value, or functionf to a containedOk value.

This function can be used to unpack a successful resultwhile handling an error.

§Examples
letk =21;letx :Result<_,&str> =Ok("foo");assert_eq!(x.map_or_else(|e| k *2, |v| v.len()),3);letx :Result<&str,_> =Err("bar");assert_eq!(x.map_or_else(|e| k *2, |v| v.len()),42);
Source

pub const fnmap_or_default<U, F>(self, f: F) -> U
where F:FnOnce(T) -> U, U:Default,

🔬This is a nightly-only experimental API. (result_option_map_or_default #138099)

Maps aResult<T, E> to aU by applying functionf to the containedvalue if the result isOk, otherwise ifErr, returns thedefault value for the typeU.

§Examples
#![feature(result_option_map_or_default)]letx:Result<_,&str> =Ok("foo");lety:Result<&str,_> =Err("bar");assert_eq!(x.map_or_default(|x| x.len()),3);assert_eq!(y.map_or_default(|y| y.len()),0);
1.0.0 (const:unstable) ·Source

pub fnmap_err<F, O>(self, op: O) ->Result<T, F>
where O:FnOnce(E) -> F,

Maps aResult<T, E> toResult<T, F> by applying a function to acontainedErr value, leaving anOk value untouched.

This function can be used to pass through a successful result while handlingan error.

§Examples
fnstringify(x: u32) -> String {format!("error code: {x}") }letx:Result<u32, u32> =Ok(2);assert_eq!(x.map_err(stringify),Ok(2));letx:Result<u32, u32> =Err(13);assert_eq!(x.map_err(stringify),Err("error code: 13".to_string()));
1.76.0 (const:unstable) ·Source

pub fninspect<F>(self, f: F) ->Result<T, E>
where F:FnOnce(&T),

Calls a function with a reference to the contained value ifOk.

Returns the original result.

§Examples
letx: u8 ="4".parse::<u8>()    .inspect(|x|println!("original: {x}"))    .map(|x| x.pow(3))    .expect("failed to parse number");
1.76.0 (const:unstable) ·Source

pub fninspect_err<F>(self, f: F) ->Result<T, E>
where F:FnOnce(&E),

Calls a function with a reference to the contained value ifErr.

Returns the original result.

§Examples
usestd::{fs, io};fnread() -> io::Result<String> {    fs::read_to_string("address.txt")        .inspect_err(|e|eprintln!("failed to read file: {e}"))}
1.47.0 (const:unstable) ·Source

pub fnas_deref(&self) ->Result<&<T asDeref>::Target,&E>
where T:Deref,

Converts fromResult<T, E> (or&Result<T, E>) toResult<&<T as Deref>::Target, &E>.

Coerces theOk variant of the originalResult viaDerefand returns the newResult.

§Examples
letx:Result<String, u32> =Ok("hello".to_string());lety:Result<&str,&u32> =Ok("hello");assert_eq!(x.as_deref(), y);letx:Result<String, u32> =Err(42);lety:Result<&str,&u32> =Err(&42);assert_eq!(x.as_deref(), y);
1.47.0 (const:unstable) ·Source

pub fnas_deref_mut(&mut self) ->Result<&mut <T asDeref>::Target,&mut E>
where T:DerefMut,

Converts fromResult<T, E> (or&mut Result<T, E>) toResult<&mut <T as DerefMut>::Target, &mut E>.

Coerces theOk variant of the originalResult viaDerefMutand returns the newResult.

§Examples
letmuts ="HELLO".to_string();letmutx:Result<String, u32> =Ok("hello".to_string());lety:Result<&mutstr,&mutu32> =Ok(&muts);assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);letmuti =42;letmutx:Result<String, u32> =Err(42);lety:Result<&mutstr,&mutu32> =Err(&muti);assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
1.0.0 (const:unstable) ·Source

pub fniter(&self) ->Iter<'_, T>

Returns an iterator over the possibly contained value.

The iterator yields one value if the result isResult::Ok, otherwise none.

§Examples
letx:Result<u32,&str> =Ok(7);assert_eq!(x.iter().next(),Some(&7));letx:Result<u32,&str> =Err("nothing!");assert_eq!(x.iter().next(),None);
1.0.0 (const:unstable) ·Source

pub fniter_mut(&mut self) ->IterMut<'_, T>

Returns a mutable iterator over the possibly contained value.

The iterator yields one value if the result isResult::Ok, otherwise none.

§Examples
letmutx:Result<u32,&str> =Ok(7);matchx.iter_mut().next() {Some(v) =>*v =40,None=> {},}assert_eq!(x,Ok(40));letmutx:Result<u32,&str> =Err("nothing!");assert_eq!(x.iter_mut().next(),None);
1.4.0 ·Source

pub fnexpect(self, msg: &str) -> T
where E:Debug,

Returns the containedOk value, consuming theself value.

Because this function may panic, its use is generally discouraged.Instead, prefer to use pattern matching and handle theErrcase explicitly, or callunwrap_or,unwrap_or_else, orunwrap_or_default.

§Panics

Panics if the value is anErr, with a panic message including thepassed message, and the content of theErr.

§Examples
letx:Result<u32,&str> =Err("emergency failure");x.expect("Testing expect");// panics with `Testing expect: emergency failure`
§Recommended Message Style

We recommend thatexpect messages are used to describe the reason youexpect theResult should beOk.

letpath = std::env::var("IMPORTANT_PATH")    .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`");

Hint: If you’re having trouble remembering how to phrase expecterror messages remember to focus on the word “should” as in “envvariable should be set by blah” or “the given binary should be availableand executable by the current user”.

For more detail on expect message styles and the reasoning behind our recommendation pleaserefer to the section on“Common MessageStyles” in thestd::error module docs.

1.0.0 ·Source

pub fnunwrap(self) -> T
where E:Debug,

Returns the containedOk value, consuming theself value.

Because this function may panic, its use is generally discouraged.Panics are meant for unrecoverable errors, andmay abort the entire program.

Instead, prefer to usethe? (try) operator, or pattern matchingto handle theErr case explicitly, or callunwrap_or,unwrap_or_else, orunwrap_or_default.

§Panics

Panics if the value is anErr, with a panic message provided by theErr’s value.

§Examples

Basic usage:

letx:Result<u32,&str> =Ok(2);assert_eq!(x.unwrap(),2);
letx:Result<u32,&str> =Err("emergency failure");x.unwrap();// panics with `emergency failure`
1.16.0 (const:unstable) ·Source

pub fnunwrap_or_default(self) -> T
where T:Default,

Returns the containedOk value or a default

Consumes theself argument then, ifOk, returns the containedvalue, otherwise ifErr, returns the default value for thattype.

§Examples

Converts a string to an integer, turning poorly-formed stringsinto 0 (the default value for integers).parse convertsa string to any other type that implementsFromStr, returning anErr on error.

letgood_year_from_input ="1909";letbad_year_from_input ="190blarg";letgood_year = good_year_from_input.parse().unwrap_or_default();letbad_year = bad_year_from_input.parse().unwrap_or_default();assert_eq!(1909, good_year);assert_eq!(0, bad_year);
1.17.0 ·Source

pub fnexpect_err(self, msg: &str) -> E
where T:Debug,

Returns the containedErr value, consuming theself value.

§Panics

Panics if the value is anOk, with a panic message including thepassed message, and the content of theOk.

§Examples
letx:Result<u32,&str> =Ok(10);x.expect_err("Testing expect_err");// panics with `Testing expect_err: 10`
1.0.0 ·Source

pub fnunwrap_err(self) -> E
where T:Debug,

Returns the containedErr value, consuming theself value.

§Panics

Panics if the value is anOk, with a custom panic message providedby theOk’s value.

§Examples
letx:Result<u32,&str> =Ok(2);x.unwrap_err();// panics with `2`
letx:Result<u32,&str> =Err("emergency failure");assert_eq!(x.unwrap_err(),"emergency failure");
Source

pub const fninto_ok(self) -> T
where E:Into<!>,

🔬This is a nightly-only experimental API. (unwrap_infallible #61695)

Returns the containedOk value, but never panics.

Unlikeunwrap, this method is known to never panic on theresult types it is implemented for. Therefore, it can be usedinstead ofunwrap as a maintainability safeguard that will failto compile if the error type of theResult is later changedto an error that can actually occur.

§Examples
fnonly_good_news() ->Result<String, !> {Ok("this is fine".into())}lets: String = only_good_news().into_ok();println!("{s}");
Source

pub const fninto_err(self) -> E
where T:Into<!>,

🔬This is a nightly-only experimental API. (unwrap_infallible #61695)

Returns the containedErr value, but never panics.

Unlikeunwrap_err, this method is known to never panic on theresult types it is implemented for. Therefore, it can be usedinstead ofunwrap_err as a maintainability safeguard that will failto compile if the ok type of theResult is later changedto a type that can actually occur.

§Examples
fnonly_bad_news() ->Result<!, String> {Err("Oops, it failed".into())}leterror: String = only_bad_news().into_err();println!("{error}");
1.0.0 (const:unstable) ·Source

pub fnand<U>(self, res:Result<U, E>) ->Result<U, E>

Returnsres if the result isOk, otherwise returns theErr value ofself.

Arguments passed toand are eagerly evaluated; if you are passing theresult of a function call, it is recommended to useand_then, which islazily evaluated.

§Examples
letx:Result<u32,&str> =Ok(2);lety:Result<&str,&str> =Err("late error");assert_eq!(x.and(y),Err("late error"));letx:Result<u32,&str> =Err("early error");lety:Result<&str,&str> =Ok("foo");assert_eq!(x.and(y),Err("early error"));letx:Result<u32,&str> =Err("not a 2");lety:Result<&str,&str> =Err("late error");assert_eq!(x.and(y),Err("not a 2"));letx:Result<u32,&str> =Ok(2);lety:Result<&str,&str> =Ok("different result type");assert_eq!(x.and(y),Ok("different result type"));
1.0.0 (const:unstable) ·Source

pub fnand_then<U, F>(self, op: F) ->Result<U, E>
where F:FnOnce(T) ->Result<U, E>,

Callsop if the result isOk, otherwise returns theErr value ofself.

This function can be used for control flow based onResult values.

§Examples
fnsq_then_to_string(x: u32) ->Result<String,&'staticstr> {    x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed")}assert_eq!(Ok(2).and_then(sq_then_to_string),Ok(4.to_string()));assert_eq!(Ok(1_000_000).and_then(sq_then_to_string),Err("overflowed"));assert_eq!(Err("not a number").and_then(sq_then_to_string),Err("not a number"));

Often used to chain fallible operations that may returnErr.

usestd::{io::ErrorKind, path::Path};// Note: on Windows "/" maps to "C:\"letroot_modified_time = Path::new("/").metadata().and_then(|md| md.modified());assert!(root_modified_time.is_ok());letshould_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified());assert!(should_fail.is_err());assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
1.0.0 (const:unstable) ·Source

pub fnor<F>(self, res:Result<T, F>) ->Result<T, F>

Returnsres if the result isErr, otherwise returns theOk value ofself.

Arguments passed toor are eagerly evaluated; if you are passing theresult of a function call, it is recommended to useor_else, which islazily evaluated.

§Examples
letx:Result<u32,&str> =Ok(2);lety:Result<u32,&str> =Err("late error");assert_eq!(x.or(y),Ok(2));letx:Result<u32,&str> =Err("early error");lety:Result<u32,&str> =Ok(2);assert_eq!(x.or(y),Ok(2));letx:Result<u32,&str> =Err("not a 2");lety:Result<u32,&str> =Err("late error");assert_eq!(x.or(y),Err("late error"));letx:Result<u32,&str> =Ok(2);lety:Result<u32,&str> =Ok(100);assert_eq!(x.or(y),Ok(2));
1.0.0 (const:unstable) ·Source

pub fnor_else<F, O>(self, op: O) ->Result<T, F>
where O:FnOnce(E) ->Result<T, F>,

Callsop if the result isErr, otherwise returns theOk value ofself.

This function can be used for control flow based on result values.

§Examples
fnsq(x: u32) ->Result<u32, u32> {Ok(x * x) }fnerr(x: u32) ->Result<u32, u32> {Err(x) }assert_eq!(Ok(2).or_else(sq).or_else(sq),Ok(2));assert_eq!(Ok(2).or_else(err).or_else(sq),Ok(2));assert_eq!(Err(3).or_else(sq).or_else(err),Ok(9));assert_eq!(Err(3).or_else(err).or_else(err),Err(3));
1.0.0 (const:unstable) ·Source

pub fnunwrap_or(self, default: T) -> T

Returns the containedOk value or a provided default.

Arguments passed tounwrap_or are eagerly evaluated; if you are passingthe result of a function call, it is recommended to useunwrap_or_else,which is lazily evaluated.

§Examples
letdefault =2;letx:Result<u32,&str> =Ok(9);assert_eq!(x.unwrap_or(default),9);letx:Result<u32,&str> =Err("error");assert_eq!(x.unwrap_or(default), default);
1.0.0 (const:unstable) ·Source

pub fnunwrap_or_else<F>(self, op: F) -> T
where F:FnOnce(E) -> T,

Returns the containedOk value or computes it from a closure.

§Examples
fncount(x:&str) -> usize { x.len() }assert_eq!(Ok(2).unwrap_or_else(count),2);assert_eq!(Err("foo").unwrap_or_else(count),3);
1.58.0 (const:unstable) ·Source

pub unsafe fnunwrap_unchecked(self) -> T

Returns the containedOk value, consuming theself value,without checking that the value is not anErr.

§Safety

Calling this method on anErr isundefined behavior.

§Examples
letx:Result<u32,&str> =Ok(2);assert_eq!(unsafe{ x.unwrap_unchecked() },2);
letx:Result<u32,&str> =Err("emergency failure");unsafe{ x.unwrap_unchecked() };// Undefined behavior!
1.58.0 ·Source

pub unsafe fnunwrap_err_unchecked(self) -> E

Returns the containedErr value, consuming theself value,without checking that the value is not anOk.

§Safety

Calling this method on anOk isundefined behavior.

§Examples
letx:Result<u32,&str> =Ok(2);unsafe{ x.unwrap_err_unchecked() };// Undefined behavior!
letx:Result<u32,&str> =Err("emergency failure");assert_eq!(unsafe{ x.unwrap_err_unchecked() },"emergency failure");
Source§

impl<T, E>Result<&T, E>

1.59.0 (const: 1.83.0) ·Source

pub const fncopied(self) ->Result<T, E>
where T:Copy,

Maps aResult<&T, E> to aResult<T, E> by copying the contents of theOk part.

§Examples
letval =12;letx:Result<&i32, i32> =Ok(&val);assert_eq!(x,Ok(&12));letcopied = x.copied();assert_eq!(copied,Ok(12));
1.59.0 ·Source

pub fncloned(self) ->Result<T, E>
where T:Clone,

Maps aResult<&T, E> to aResult<T, E> by cloning the contents of theOk part.

§Examples
letval =12;letx:Result<&i32, i32> =Ok(&val);assert_eq!(x,Ok(&12));letcloned = x.cloned();assert_eq!(cloned,Ok(12));
Source§

impl<T, E>Result<&mut T, E>

1.59.0 (const: 1.83.0) ·Source

pub const fncopied(self) ->Result<T, E>
where T:Copy,

Maps aResult<&mut T, E> to aResult<T, E> by copying the contents of theOk part.

§Examples
letmutval =12;letx:Result<&muti32, i32> =Ok(&mutval);assert_eq!(x,Ok(&mut12));letcopied = x.copied();assert_eq!(copied,Ok(12));
1.59.0 ·Source

pub fncloned(self) ->Result<T, E>
where T:Clone,

Maps aResult<&mut T, E> to aResult<T, E> by cloning the contents of theOk part.

§Examples
letmutval =12;letx:Result<&muti32, i32> =Ok(&mutval);assert_eq!(x,Ok(&mut12));letcloned = x.cloned();assert_eq!(cloned,Ok(12));
Source§

impl<T, E>Result<Option<T>, E>

1.33.0 (const: 1.83.0) ·Source

pub const fntranspose(self) ->Option<Result<T, E>>

Transposes aResult of anOption into anOption of aResult.

Ok(None) will be mapped toNone.Ok(Some(_)) andErr(_) will be mapped toSome(Ok(_)) andSome(Err(_)).

§Examples
#[derive(Debug, Eq, PartialEq)]structSomeErr;letx:Result<Option<i32>, SomeErr> =Ok(Some(5));lety:Option<Result<i32, SomeErr>> =Some(Ok(5));assert_eq!(x.transpose(), y);
Source§

impl<T, E>Result<Result<T, E>, E>

1.89.0 (const: 1.89.0) ·Source

pub const fnflatten(self) ->Result<T, E>

Converts fromResult<Result<T, E>, E> toResult<T, E>

§Examples
letx:Result<Result<&'staticstr, u32>, u32> =Ok(Ok("hello"));assert_eq!(Ok("hello"), x.flatten());letx:Result<Result<&'staticstr, u32>, u32> =Ok(Err(6));assert_eq!(Err(6), x.flatten());letx:Result<Result<&'staticstr, u32>, u32> =Err(6);assert_eq!(Err(6), x.flatten());

Flattening only removes one level of nesting at a time:

letx:Result<Result<Result<&'staticstr, u32>, u32>, u32> =Ok(Ok(Ok("hello")));assert_eq!(Ok(Ok("hello")), x.flatten());assert_eq!(Ok("hello"), x.flatten().flatten());

Trait Implementations§

1.0.0 ·Source§

impl<T, E>Clone forResult<T, E>
where T:Clone, E:Clone,

Source§

fnclone(&self) ->Result<T, E>

Returns a duplicate of the value.Read more
Source§

fnclone_from(&mut self, source: &Result<T, E>)

Performs copy-assignment fromsource.Read more
1.0.0 ·Source§

impl<T, E>Debug forResult<T, E>
where T:Debug, E:Debug,

Source§

fnfmt(&self, f: &mutFormatter<'_>) ->Result<(),Error>

Formats the value using the given formatter.Read more
1.0.0 ·Source§

impl<A, E, V>FromIterator<Result<A, E>> forResult<V, E>
where V:FromIterator<A>,

Source§

fnfrom_iter<I>(iter: I) ->Result<V, E>
where I:IntoIterator<Item =Result<A, E>>,

Takes each element in theIterator: if it is anErr, no furtherelements are taken, and theErr is returned. Should noErr occur, acontainer with the values of eachResult is returned.

Here is an example which increments every integer in a vector,checking for overflow:

letv =vec![1,2];letres:Result<Vec<u32>,&'staticstr> = v.iter().map(|x:&u32|    x.checked_add(1).ok_or("Overflow!")).collect();assert_eq!(res,Ok(vec![2,3]));

Here is another example that tries to subtract one from another listof integers, this time checking for underflow:

letv =vec![1,2,0];letres:Result<Vec<u32>,&'staticstr> = v.iter().map(|x:&u32|    x.checked_sub(1).ok_or("Underflow!")).collect();assert_eq!(res,Err("Underflow!"));

Here is a variation on the previous example, showing that nofurther elements are taken fromiter after the firstErr.

letv =vec![3,2,1,10];letmutshared =0;letres:Result<Vec<u32>,&'staticstr> = v.iter().map(|x:&u32| {    shared += x;    x.checked_sub(2).ok_or("Underflow!")}).collect();assert_eq!(res,Err("Underflow!"));assert_eq!(shared,6);

Since the third element caused an underflow, no further elements were taken,so the final value ofshared is 6 (=3 + 2 + 1), not 16.

Source§

impl<T, E, F>FromResidual<Result<Infallible, E>> forPoll<Option<Result<T, F>>>
where F:From<E>,

Source§

fnfrom_residual(x:Result<Infallible, E>) ->Poll<Option<Result<T, F>>>

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)
Constructs the type from a compatibleResidual type.Read more
Source§

impl<T, E, F>FromResidual<Result<Infallible, E>> forPoll<Result<T, F>>
where F:From<E>,

Source§

fnfrom_residual(x:Result<Infallible, E>) ->Poll<Result<T, F>>

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)
Constructs the type from a compatibleResidual type.Read more
Source§

impl<T, E, F>FromResidual<Result<Infallible, E>> forResult<T, F>
where F:From<E>,

Source§

fnfrom_residual(residual:Result<Infallible, E>) ->Result<T, F>

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)
Constructs the type from a compatibleResidual type.Read more
Source§

impl<T, E, F>FromResidual<Yeet<E>> forResult<T, F>
where F:From<E>,

Source§

fnfrom_residual(_:Yeet<E>) ->Result<T, F>

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)
Constructs the type from a compatibleResidual type.Read more
1.0.0 ·Source§

impl<T, E>Hash forResult<T, E>
where T:Hash, E:Hash,

Source§

fnhash<__H>(&self, state:&mut __H)
where __H:Hasher,

Feeds this value into the givenHasher.Read more
1.3.0 ·Source§

fnhash_slice<H>(data: &[Self], state:&mut H)
where H:Hasher, Self:Sized,

Feeds a slice of this type into the givenHasher.Read more
1.4.0 ·Source§

impl<'a, T, E>IntoIterator for &'aResult<T, E>

Source§

typeItem =&'a T

The type of the elements being iterated over.
Source§

typeIntoIter =Iter<'a, T>

Which kind of iterator are we turning this into?
Source§

fninto_iter(self) ->Iter<'a, T>

Creates an iterator from a value.Read more
1.4.0 ·Source§

impl<'a, T, E>IntoIterator for &'a mutResult<T, E>

Source§

typeItem =&'a mut T

The type of the elements being iterated over.
Source§

typeIntoIter =IterMut<'a, T>

Which kind of iterator are we turning this into?
Source§

fninto_iter(self) ->IterMut<'a, T>

Creates an iterator from a value.Read more
1.0.0 ·Source§

impl<T, E>IntoIterator forResult<T, E>

Source§

fninto_iter(self) ->IntoIter<T>

Returns a consuming iterator over the possibly contained value.

The iterator yields one value if the result isResult::Ok, otherwise none.

§Examples
letx:Result<u32,&str> =Ok(5);letv: Vec<u32> = x.into_iter().collect();assert_eq!(v, [5]);letx:Result<u32,&str> =Err("nothing!");letv: Vec<u32> = x.into_iter().collect();assert_eq!(v, []);
Source§

typeItem = T

The type of the elements being iterated over.
Source§

typeIntoIter =IntoIter<T>

Which kind of iterator are we turning this into?
1.0.0 (const:unstable) ·Source§

impl<T, E>Ord forResult<T, E>
where T:Ord, E:Ord,

Source§

fncmp(&self, other: &Result<T, E>) ->Ordering

This method returns anOrdering betweenself andother.Read more
1.21.0 ·Source§

fnmax(self, other: Self) -> Self
where Self:Sized,

Compares and returns the maximum of two values.Read more
1.21.0 ·Source§

fnmin(self, other: Self) -> Self
where Self:Sized,

Compares and returns the minimum of two values.Read more
1.50.0 ·Source§

fnclamp(self, min: Self, max: Self) -> Self
where Self:Sized,

Restrict a value to a certain interval.Read more
1.0.0 (const:unstable) ·Source§

impl<T, E>PartialEq forResult<T, E>
where T:PartialEq, E:PartialEq,

Source§

fneq(&self, other: &Result<T, E>) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

Tests for!=. The default implementation is almost always sufficient,and should not be overridden without very good reason.
1.0.0 (const:unstable) ·Source§

impl<T, E>PartialOrd forResult<T, E>

Source§

fnpartial_cmp(&self, other: &Result<T, E>) ->Option<Ordering>

This method returns an ordering betweenself andother values if one exists.Read more
1.0.0 ·Source§

fnlt(&self, other:&Rhs) ->bool

Tests less than (forself andother) and is used by the< operator.Read more
1.0.0 ·Source§

fnle(&self, other:&Rhs) ->bool

Tests less than or equal to (forself andother) and is used by the<= operator.Read more
1.0.0 ·Source§

fngt(&self, other:&Rhs) ->bool

Tests greater than (forself andother) and is used by the>operator.Read more
1.0.0 ·Source§

fnge(&self, other:&Rhs) ->bool

Tests greater than or equal to (forself andother) and is used bythe>= operator.Read more
1.16.0 ·Source§

impl<T, U, E>Product<Result<U, E>> forResult<T, E>
where T:Product<U>,

Source§

fnproduct<I>(iter: I) ->Result<T, E>
where I:Iterator<Item =Result<U, E>>,

Takes each element in theIterator: if it is anErr, no furtherelements are taken, and theErr is returned. Should noErroccur, the product of all elements is returned.

§Examples

This multiplies each number in a vector of strings,if a string could not be parsed the operation returnsErr:

letnums =vec!["5","10","1","2"];lettotal:Result<usize,_> = nums.iter().map(|w| w.parse::<usize>()).product();assert_eq!(total,Ok(100));letnums =vec!["5","10","one","2"];lettotal:Result<usize,_> = nums.iter().map(|w| w.parse::<usize>()).product();assert!(total.is_err());
Source§

impl<T, E>Residual<T> forResult<Infallible, E>

Source§

typeTryType =Result<T, E>

🔬This is a nightly-only experimental API. (try_trait_v2_residual #91285)
The “return” type of this meta-function.
1.16.0 ·Source§

impl<T, U, E>Sum<Result<U, E>> forResult<T, E>
where T:Sum<U>,

Source§

fnsum<I>(iter: I) ->Result<T, E>
where I:Iterator<Item =Result<U, E>>,

Takes each element in theIterator: if it is anErr, no furtherelements are taken, and theErr is returned. Should noErroccur, the sum of all elements is returned.

§Examples

This sums up every integer in a vector, rejecting the sum if a negativeelement is encountered:

letf = |&x:&i32|ifx <0{Err("Negative element found") }else{Ok(x) };letv =vec![1,2];letres:Result<i32,_> = v.iter().map(f).sum();assert_eq!(res,Ok(3));letv =vec![1, -2];letres:Result<i32,_> = v.iter().map(f).sum();assert_eq!(res,Err("Negative element found"));
1.61.0 ·Source§

impl<T:Termination, E:Debug>Termination forResult<T, E>

Source§

fnreport(self) ->ExitCode

Is called to get the representation of the value as status code.This status code is returned to the operating system.
Source§

impl<T, E>Try forResult<T, E>

Source§

typeOutput = T

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)
The type of the value produced by? whennot short-circuiting.
Source§

typeResidual =Result<Infallible, E>

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)
The type of the value passed toFromResidual::from_residualas part of? when short-circuiting.Read more
Source§

fnfrom_output(output: <Result<T, E> asTry>::Output) ->Result<T, E>

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)
Constructs the type from itsOutput type.Read more
Source§

fnbranch( self,) ->ControlFlow<<Result<T, E> asTry>::Residual, <Result<T, E> asTry>::Output>

🔬This is a nightly-only experimental API. (try_trait_v2 #84277)
Used in? to decide whether the operator should produce a value(because this returnedControlFlow::Continue)or propagate a value back to the caller(because this returnedControlFlow::Break).Read more
Source§

impl<T, E>CloneFromCell forResult<T, E>

1.0.0 ·Source§

impl<T, E>Copy forResult<T, E>
where T:Copy, E:Copy,

1.0.0 (const:unstable) ·Source§

impl<T, E>Eq forResult<T, E>
where T:Eq, E:Eq,

1.0.0 ·Source§

impl<T, E>StructuralPartialEq forResult<T, E>

Source§

impl<T, E>UseCloned forResult<T, E>
where T:UseCloned, E:UseCloned,

Auto Trait Implementations§

§

impl<T, E>Freeze forResult<T, E>
where T:Freeze, E:Freeze,

§

impl<T, E>RefUnwindSafe forResult<T, E>

§

impl<T, E>Send forResult<T, E>
where T:Send, E:Send,

§

impl<T, E>Sync forResult<T, E>
where T:Sync, E:Sync,

§

impl<T, E>Unpin forResult<T, E>
where T:Unpin, E:Unpin,

§

impl<T, E>UnwindSafe forResult<T, E>

Blanket Implementations§

Source§

impl<T>Any for T
where T: 'static + ?Sized,

Source§

fntype_id(&self) ->TypeId

Gets theTypeId ofself.Read more
Source§

impl<T>Borrow<T> for T
where T: ?Sized,

Source§

fnborrow(&self) ->&T

Immutably borrows from an owned value.Read more
Source§

impl<T>BorrowMut<T> for T
where T: ?Sized,

Source§

fnborrow_mut(&mut self) ->&mut T

Mutably borrows from an owned value.Read more
Source§

impl<T>CloneToUninit for T
where T:Clone,

Source§

unsafe fnclone_to_uninit(&self, dest:*mutu8)

🔬This is a nightly-only experimental API. (clone_to_uninit #126799)
Performs copy-assignment fromself todest.Read more
Source§

impl<T>From<T> for T

Source§

fnfrom(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U>Into<U> for T
where U:From<T>,

Source§

fninto(self) -> U

CallsU::from(self).

That is, this conversion is whatever the implementation ofFrom<T> for U chooses to do.

Source§

impl<T>ToOwned for T
where T:Clone,

Source§

typeOwned = T

The resulting type after obtaining ownership.
Source§

fnto_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning.Read more
Source§

fnclone_into(&self, target:&mut T)

Uses borrowed data to replace owned data, usually by cloning.Read more
Source§

impl<T, U>TryFrom<U> for T
where U:Into<T>,

Source§

typeError =Infallible

The type returned in the event of a conversion error.
Source§

fntry_from(value: U) ->Result<T, <T asTryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U>TryInto<U> for T
where U:TryFrom<T>,

Source§

typeError = <U asTryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fntry_into(self) ->Result<U, <U asTryFrom<T>>::Error>

Performs the conversion.

[8]ページ先頭

©2009-2026 Movatter.jp