num_enum icon indicating copy to clipboard operation
num_enum copied to clipboard

Could IntoPrimitive::into() be a const function?

Open DavidAntliff opened this issue 9 months ago • 1 comments

Would it be possible for MyEnum.into() to be a const function?

Then I could use it like this, for example with something like the bitfield-struct crate:

#[derive(Debug, IntoPrimitive)]
#[repr(u16)]
enum Opcode {
    Jump = 1,
    Halt = 2,
    // ... etc
}

#[bitfield(u32)]
pub(crate) struct JumpInstruction {
    #[bits(16)]
    address: Address,
    #[bits(16, default=Opcode::Jump.into())]
    opcode: u16,
}

Unfortunately, as things stand:

error[E0015]: cannot call non-const fn `<Opcode as Into<u8>>::into` in constant functions
  --> src/ops.rs:75:36
   |
75 |     #[bits(16, default=Opcode::Jump.into())]
   |                                     ^^^^^^
   |

Is this technically possible? The discriminants of the enum variants are static const, I assume? However, I think I read that trait function implementations cannot be const fn in stable Rust.

DavidAntliff avatar May 16 '24 05:05 DavidAntliff