mq7
mq7

Reputation: 1299

How do I write an unimplemented function that returns impl Trait without dummy code?

I tried this:

trait T {}

fn f() -> impl T {
    unimplemented!();
}

fn main() {
    f();
}

But it gives this error:

error[E0277]: the trait bound `!: T` is not satisfied
 --> src/main.rs:3:11
  |
3 | fn f() -> impl T {
  |           ^^^^^^ the trait `T` is not implemented for `!`
  |
  = note: the return type of a function must have a statically known size

This compiles if a branch in f returns something:

struct S {}

trait T {}

impl T for S {}

fn f(a: u32) -> impl T {
    if a == 0 {
        panic!();
    } else {
        S {}
    }
}

fn main() {
    f(5);
}

Upvotes: 3

Views: 715

Answers (1)

Shepmaster
Shepmaster

Reputation: 432199

This is a known issue.

The easy (cheating) answer is to implement your trait for !:

impl T for ! {}

You can see in the tracking issue for promoting ! to a type that much discussion has been around which traits to implement for a type.

There was also an RFC to implement traits automatically for !, but it was not accepted. This requires "implementing" any methods in the trait because another proposed RFC was also postponed:

trait T {
    fn hello(&self) -> u32;
}

impl T for ! {
    fn hello(&self) -> u32 {
        *self
    }
}

Upvotes: 2

Related Questions