3

I was trying to write the following code:

trait Foo {
    type Output;

    fn bar() -> Self::Output;
    fn baz() -> Self::Output {
        const match Self::Output { // imaginary syntax
            () => (),        // compile this statement only if Output == Unit
            _ => bar()       // Otherwise compile this statement
        }
    }
}

Since Output is a generic type, I can't instantiate a value (and it could be expensive to do so). In C++, I would have just used if constexpr(std::same<Output, void>::value) or created a template function and specialized it for void, but I didn't find a way to do it in Rust.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Robin
  • 423
  • 3
  • 10
  • Expanding on the duplicate suggestion, add another trait that `Self::Output` must implement and then implement the new trait for the unit type and others. [applied](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=2086f149beef80b9b525343a2d358e0c) – Shepmaster Nov 14 '19 at 00:30

0 Answers0