Unexpected enum display behaviour


I was working with a custom error type defined as an enum and ran into an issue where printing it would cause my stack to overflow. I took the problem code and reduced it down to the simplest version that would cause the error.

It looks like the issue was in implementing the Display trait and writing the enum itself, instead of one of the values.

    pub enum TestEnum {

    impl fmt::Display for TestEnum {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "TestEnum: {}", *self)

Whole program here - https://play.rust-lang.org/?gist=70d8dfd01bae4ae50ab94737408f4139&version=undefined

I was able to fix the issues by only printing values of the enum, not the enum itself.

My question is why does this happen? It isn’t immediately obvious that this would cause an infinite recursive print and the compiler doesn’t give any warnings.


The {} here will call Display for TestEnum again.

fmt::Arguments erases a lot of type info, so I suspect it’s just abstracted too much for the compiler to see that this is unconditional recursion.


Oh ok, that explains it. Thanks!