Home > Net >  PartialEQ explicit implementation for enum triggers thread 'main' has overflowed its stack
PartialEQ explicit implementation for enum triggers thread 'main' has overflowed its stack

Time:03-07

Explicit implementation of PartialEQ for Enum is triggering a stack overflow when having a struct with an array with an enum:

#[derive(Debug, Copy, Clone)]
enum MyEnum {
    A,
}

impl PartialEq for MyEnum {
    fn eq(&self, other: &Self) -> bool {
        self == other
    }
}

#[derive(Debug)]
struct MyStruct {
    cells: [MyEnum; 1],
}

fn main() {
    let init_struct = MyStruct {
        cells: [MyEnum::A]
    };

    assert_eq!(init_struct.cells[0], MyEnum::A);
}

Output from the terminal:

➜  enum-bug git:(master) ✗ cargo run
   Compiling enum-bug v0.1.0 
    Finished dev [unoptimized   debuginfo] target(s) in 0.27s
     Running `target/debug/enum-bug`

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
[1]    2361 abort      cargo run

But when commenting out the explicit implementation of PartialEQ, and adding it to #[derive] everything works successfully:

#[derive(Debug, Copy, Clone, PartialEq)]
enum MyEnum {
    A,
}

/*
impl PartialEq for MyEnum {
    fn eq(&self, other: &Self) -> bool {
        self == other
    }
}
*/

#[derive(Debug)]
struct MyStruct {
    cells: [MyEnum; 1],
}

fn main() {
    let init_struct = MyStruct {
        cells: [MyEnum::A]
    };

    assert_eq!(init_struct.cells[0], MyEnum::A);
}

So what's wrong with the explicit PartialEQ implementation for the enum?

CodePudding user response:

As others have pointed out in the comments, == looks for a PartialEq implemetation, so your code infinitely recurses.

Instead, you can use match:

enum Foo {
  A,
  B,
}

impl PartialEq for Foo {
  fn eq(&self, other: &Self) -> bool {
    match (self, other) {
      (Self::A, Self::A) => true,
      (Self::B, Self::B) => true,
      _ => false
    }
  }
}

Though I'd recommend just deriving it for most PartialEq implementations, unless you have good reason not to.

  • Related