lotsoftools

Understanding Rust Error E0370: Enum Discriminant Overflow

What is Rust Error E0370?

Rust Error E0370 occurs when an enum declaration reaches its maximum value for the given data type and overflows. The Rust compiler is unable to automatically assign the next value to the enum variant. This error is observed when the enum is explicitly given a representation using the #[repr()] attribute, and one of the enum variants exceeds the maximum value for the specified data type.

Breaking Down the Error Message

Consider the following erroneous code example:

#![allow(unused)]
fn main() {
#[repr(i64)]
enum Foo {
    X = 0x7fffffffffffffff,
    Y, // error: enum discriminant overflowed on value after
       //        9223372036854775807: i64; set explicitly via
       //        Y = -9223372036854775808 if that is desired outcome
}
}

Here, we have an enum Foo with a representation of i64. The variant X is assigned the maximum value for i64 (0x7fffffffffffffff or 9223372036854775807). Consequently, the compiler is unable to automatically assign the next value to the variant Y as it would lead to overflow.

Fixing the Error

To resolve Rust Error E0370, one of the following solutions can be applied:

1. Set the next enum value manually

In this case, we can manually set the value for Y, ensuring it doesn't exceed the maximum value for i64.

#![allow(unused)]
fn main() {
#[repr(i64)]
enum Foo {
    X = 0x7fffffffffffffff,
    Y = 0, // ok!
}
}

2. Rearrange enum variants

Move the enum variant with the maximum value to the end of the enum to prevent overflow during discriminant value assignment.

#![allow(unused)]
fn main() {
#[repr(i64)]
enum Foo {
    Y = 0, // ok!
    X = 0x7fffffffffffffff,
}
}

By following either of these recommended solutions, the error will be resolved.

Recommended Reading