Understanding Rust Error E0732

Introduction to Rust Error E0732

Rust Error E0732 occurs when an enum with a discriminant doesn't specify a #[repr(inttype)]. In this article, we will explore the underlying cause of this error and demonstrate how to fix it.

Erroneous Code Example

enum Enum { // error!
    Unit = 1,
    Tuple() = 2,
    Struct{} = 3,

fn main() {}

Discriminants in Enums

A discriminant is an explicit integer value given to an enum variant. This helps to ensure that there is a well-defined way to extract a variant's discriminant from a value. Error E0732 arises when a #[repr(inttype)] is missing on such enums. The #[repr(inttype)] attribute is used to specify the integer type that will represent the discriminant.

Correct Code Example with #[repr(inttype)]

enum Enum {
    Unit = 3,
    Tuple(u16) = 2,
    Struct {
        a: u8,
        b: u16,
    } = 1,

fn discriminant(v : &Enum) -> u8 {
    unsafe { *(v as *const Enum as *const u8) }

fn main() {
    assert_eq!(3, discriminant(&Enum::Unit));
    assert_eq!(2, discriminant(&Enum::Tuple(5)));
    assert_eq!(1, discriminant(&Enum::Struct{a: 7, b: 11}));

Explanation and Solution

In the corrected code, we have added the #[repr(u8)] attribute to indicate that the discriminant should be represented using the u8 integer type. This resolves the error and allows the code to compile successfully.