Skip to content

Perform Ok-wrapping in try_block macro #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

joseph-gio
Copy link

This modifies the macro to perform Ok-wrapping on the final value. Not only is this more ergonomic, this is how the full try block feature will behave when it is eventually stabilized: rust-lang/rust#70941. Since this macro is meant to emulate the try block feature while we wait for stabilization, it makes sense that it should try to behave as closely to that feature as possible.

This will obviously be a breaking change, but since the crate has not reached 1.0 yet, that should not be a problem.

Any type which implements the `FromOk` trait can be used in the `try_block` macro.

Another candidate for implementation is `std::ops::ControlFlow`. However, that would require bumping the MSV to rust 1.55.
src/lib.rs Outdated
}}
}

/// A type that can Ok-wrap some value, for use in the [`try_block`] macro.
pub trait FromOk {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can actually avoid the need for this trait with a bit of trickery. Try::from_output is unstable, but you can get to it via try_fold: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0b07b516d97996ac386886ee21d8c561

macro_rules! do_ok_wrapping {
    ($e:expr) => {
        std::iter::empty()
            .try_fold($e, |_, ()| unreachable!())
    };
}

fn main() {
    let _: Option<i32> = do_ok_wrapping!(3);
    let _: std::io::Result<i32> = do_ok_wrapping!(5);
}

(That might make the error messages horrible, though.)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can even remove the panic by using the never type instead of unit.

std::iter::empty()
    .try_fold($e, |_, x: !| match x { })

I think this repo is unmaintained so I'm going to fork it, and I'll definitely use your idea.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, nice touch! An uninhabited enum -- no need for ! specifically -- is a great idea.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants