auto_enums icon indicating copy to clipboard operation
auto_enums copied to clipboard

Support `Into`/`From` trait

Open vic1707 opened this issue 10 months ago • 3 comments

Assuming all code paths implements the same Into/From "destination" it could be nice to let auto_enums generate those traits impls. This can, I think, theorically be done in the custom derive attribute, keeping existing functionality as they are.

use auto_enums::auto_enum;

struct Toto(u64);
impl <T: Into<u64>> Into<Toto> for T {
    // ...
}

#[auto_enum(Into<Toto>)]
fn example(x: u8) {
    match x {
        0 => 12_u8,
        1 => 42_u16,
        _ => 69_u64,
    }
}

Where the generated code would look like

impl Into<Toto> for $enum_name {
    fn into(value: $enum_name) -> Toto {
        // simply blindly call .into() for each arm
    }
}

Oversimplified code but I think everyone reading this gets the idea.

Would you be open to a PR for this?

vic1707 avatar Feb 10 '25 20:02 vic1707

It seems that supporting Into/TryInto is fine. I would accept a PR to do that.

taiki-e avatar Feb 10 '25 20:02 taiki-e

Thanks, I'll start to work on Into that soon ™️ 👌 As for TryInto (which I'll probably do in a 2nd PR) how do you think the error type should be treated?

Should it be named enum_derive(TryInto<Target, CustomError>)? Should it be extracted from the first variant error type for its TryInto<Target> implémentation (kinda like what's done with the Future trait? Both (allow naming, if missing auto-extract)?

Naming it has the advantage to allow users to have their match arms yield a different Error type and capturing it all by -> impl TryInto<Target, Error=CustomError>

vic1707 avatar Feb 10 '25 21:02 vic1707

As for TryInto (which I'll probably do in a 2nd PR) how do you think the error type should be treated?

Should it be named enum_derive(TryInto<Target, CustomError>)? Should it be extracted from the first variant error type for its TryInto<Target> implémentation (kinda like what's done with the Future trait? Both (allow naming, if missing auto-extract)?

Oh, that is indeed tricky. It might make sense to skip TryInto for now.

taiki-e avatar Feb 10 '25 21:02 taiki-e