Allow Try Trait to convert to whole return value

The current implementation of the Try trait (the one that is used with ?) currently does support the following transformation.

fn func_1(...) -> Result<T1, E1>;

fn func_2(...) -> Result<T2, E2> {
    ...
    let res = func_1(...)?;
    ...
}

If the following bound is the only one that exists:

impl From<E2> for Result<T1, E1>;

I think that this could be a valid use case for this operator.

You can do this with map:

fn func_1(...) -> Result<T1, E1>;

fn func_2(...) -> Result<T2, E2> {
    ...
    let res = func_1(...).map(T2::from)?;
    ...
}

Is there a reason why this is not sufficient?

Yes, if part of the From impl is for an instance of E2 to become an instance of T1.

The function you want is Result::or_else, except both Ok types must equal. The particular control flow you want is specialized enough that you may want to just write it out as a match.

Adding more implicit conversions to ? seems poorly advised (and may break existing programs, but I don't know off the top of my head if that's true).

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.