Rfcs: Implement `From<E>` for `u32` when `E` is `#[repr(u32)] enum E`

Created on 16 Nov 2018  ·  9Comments  ·  Source: rust-lang/rfcs

I think everything is in the title. I was very surprised to see that appears not to be already done, so I guess I'm missing something.

Should this go through the RFC process or just get implemented directly as an obvious thing, given eg. u32: From<u16>?

Most helpful comment

This seems to fit better as something that could be derived, but not be automatic. Representation and having the conversion available in the API are not exactly the same thing.

All 9 comments

From<T> for U implies Into<U> for T. Imagine your u32 is outside the valid discriminant range for the enum. That's undefined behaviour. Then what should the custom conversion function do? The conversion can't fail, so panic?

I think TryFrom might be a better solution here.

From<E> for u32 implies Into<u32> for E, which allows you to call enum_value.into(). That is still totally valid. Only Into<E> for u32 would be problematic, but that would only be implied by From<u32> for E, which is not what is suggested here.

Okay, yeah, I got confused. Don't mind me.

I believe the most recent discussion on enum<->integer conversions is: https://internals.rust-lang.org/t/pre-rfc-enum-from-integer/6348

This other discussion appears to be mostly about int -> enum, isn't it? Here I'm just thinking of a trait (in this case From/Into) to do the same as as u32 already does, so that I could be generic over u32 and #[repr(u32)] enums :)

This seems to fit better as something that could be derived, but not be automatic. Representation and having the conversion available in the API are not exactly the same thing.

Since we do have conversion by as casts already, it feels reasonable to also support From automatically, too

Since we do have conversion by as casts already, it feels reasonable to also support From automatically, too

I disagree. The fact that as works for this was a mistake, IMO. Something might be #[repr(u32)] without wanting to expose the actual values used for each variant, so this shouldn't be the default.

I just published a full RFC proposing making From/Into derivable on such enums, and deprecating as conversions - comments very welcome!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

silversolver1 picture silversolver1  ·  3Comments

3442853561 picture 3442853561  ·  3Comments

clarfonthey picture clarfonthey  ·  3Comments

rudolfschmidt picture rudolfschmidt  ·  3Comments

mahkoh picture mahkoh  ·  3Comments