#strict #inference #help #operator

nightly no-std strict_result

Adds a Result::strict()? function to help with type inference

4 stable releases

1.2.0 Nov 8, 2023
1.1.0 Dec 14, 2022
1.0.1 Dec 8, 2022

#212 in No standard library

Download history 9/week @ 2024-02-22 5/week @ 2024-02-29 6/week @ 2024-03-07 16/week @ 2024-03-14 6/week @ 2024-03-21 112/week @ 2024-03-28 4/week @ 2024-04-04

116 downloads per month

MIT/Apache

7KB
63 lines

strict-result

The ? operator on Result has an implicit .into() on the error type, to make it easier to upcast errors into broader error types. This however can sometimes cause problems for type inference in highly generic contexts, since it effectively turns into .into().into(), which is ambiguous. To combat this, this crate defines a separate .strict()? operator, which does not perform this implicit .into().

For an example, let's define a simple generic function:

fn passthrough<T>(f: impl FnOnce() -> T) -> T {
    f()
}

If we try to use this combined with the ? operator, we will get an error because the generic <T> cannot be determined.

passthrough(|| {
    std::fs::create_dir("example")?;
    Ok(()) // cannot infer type of the type parameter `E` declared on the enum `Result`
})?;

In this case we can use .strict()? to require that the error type is equal to the outer one.

use strict_result::Strict;

passthrough(|| {
    std::fs::create_dir("example")?;
    Ok(())
}).strict()?;

This crate uses the try_trait_v2 feature, and thus requires nightly.

No runtime deps