Skip to content

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

@DavidAntliff

Description

@DavidAntliff

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions