Why do we need FromResidual?

what's the difference between From and FromResidual traits

The purpose differs:

and what's the difference in use?

You implement From<WhateverTypes> for YourType or From<YourType> for ForeignType to allow converting generally. It's a common trait to implement. In addition, there's a blanket implementation of Into based on From. So whenever you've used .into(), it's probably due to a From implementation as well.

You only implement FromResidual if you're making a custom Try (?) implementation, and there's no reason to use it directly. It's part of ? desugaring. It's also not yet stable.


When you use ? on a Result, the Err variant may be transformed. You might have seen this approximated as

// let x = res?;
let x = match res {
    Ok(r) => r,
    Err(e) => return From::from(e),
};

But the modern desugaring doesn't use From directly, it uses FromResidual. This let's the choice of supported ? conversion be implementation specific.

2 Likes

thank you very mutch

Importantly, there's no blanket for FromResidual, and there are implementations of it which would coherence-conflict with said blanket.

And even if it were possible to write those impls in future (with some kind of specialization), it's possible that what ? wants will be different from what .into() wants. (We'll see. Could reasonably go either way on that one.)

2 Likes