Ideas around anonymous enum types

fn make_frob(x: u32) -> impl Fn(u32) -> u32 {
  if x % 2 == 0 {
    |y| y / x
  } else {
    |y| y / (x + 1)
  }
}

If the code above could be made to work, it would be a huge win for Rust.

When people are learning the language, they universally expect that code to work and are surprised when it doesn't. When teaching, I'd rather have to explain the caveat about the minor overhead due to the anonymous enum rather than having to explain the compiler error and how to work around it, and why things are so much different once you add the conditional branch. The potential problem of accidentally adding an anonymous enum seems minor in comparison. It's almost just an implementation detail.

Besides, if the mental model is that the anonymous enum is an opaque type that implements the trait, and the function body is returning that anonymous enum, then it would be terribly surprising if impl Trait didn't cover that. We wouldn't want to have to explain that, "a return type of impl Trait means that the function returns some type that implements the trait, unless that type is an anonymous enum, in which case there's a special syntax for that."

2 Likes