Expand description
Provides a derive macro for Try
(try_trait_v2)
Also enables inter-conversion from Result<T, E> where E: Into::into(Self)
and back where E: From::from<Self<!>>
§Requires:
- nightly or
RUSTC_BOOTSTRAP = 1 #![feature(never_type)]#![feature(try_trait_v2)]
§Limitations on the annotated type:
- must be an
enum - must have at least one generic type
- the first generic type must be the
Outputtype (produced when not short circuiting) - the output variant (does not short-circuit) must be the first variant and store the output type as the only unnamed field
See the individual documentation for Try for specifics on the generated code.
§Example Usage:
#![feature(never_type)]
#![feature(try_trait_v2)]
use try_v2::{Try, Try_ConvertResult};
#[derive(Try, Try_ConvertResult)]
enum TestResult<T> {
Ok(T),
TestsFailed,
OtherError(String)
}
// Basic short circuiting thanks to `#[derive(Try)]`
fn run_tests() -> TestResult<()> {
TestResult::OtherError("oops!".to_string())?; // <- Function short-circuits here ...
TestResult::TestsFailed?;
TestResult::Ok(())
}
assert!(matches!(run_tests(), TestResult::OtherError(msg) if msg == "oops!"));
// Conversion from std::result::Result thanks to `#[derive(Try_ConvertResult)]`
struct TestFailure {}
impl<T> From<TestFailure> for TestResult<T> {
fn from(err: TestFailure) -> Self {
TestResult::TestsFailed
}
}
fn run_more_tests() -> TestResult<()> {
std::result::Result::Err(TestFailure{})?; // <- Function short-circuits here & converts to a TestResult...
TestResult::Ok(())
}
assert!(matches!(run_more_tests(), TestResult::TestsFailed));§MSRV
1.85.1 if you are walking the grey-zone between stable and nightly via RUSTC_BOOTSTRAP
§Currently untested (may work, may not …):
whereclauses- storing
Fns in variants
Derive Macros§
- Try
- Derives try_trait_v2
- Try_
Convert Result - Derives ?-conversion from Result<T, E> and back where suitable implementations of From/Into exist.