Unable to use `unimplemented!()` as a stub body returning `impl ...`

The standard library documentation describes unimplemented!() as "allow[ing] your code to type-check", which I take to mean that it should be valid as the return value of a function of any return type. However, while trying to create an MVCE for a typing/lifetime issue I was running into (which I'll probably post separately later), I stumbled across this:

fn main() {
    for x in foo() {
        println!("{}", x);
    }
}

fn foo() -> impl Iterator<Item=String> {
    unimplemented!()
}

Trying to build this on stable (1.62.0) fails with:

error[E0277]: `()` is not an iterator
 --> src/main.rs:7:13
  |
7 | fn foo() -> impl Iterator<Item=String> {
  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^ `()` is not an iterator
  |
  = help: the trait `Iterator` is not implemented for `()`

Apparently, Rust thinks unimplemented!() has type () instead of type !, yet this code builds just fine:

fn main() {
    println!("{}", foo());
}

fn foo() -> String {
    unimplemented!()
}

Is this a bug in Rust, or am I doing something wrong?

I've ran into similar circumstances and it's arguably a bug, or at minimum a diagnostic issue on some level, as the root cause (as I understand it) is that ! doesn't implement Iterator. (To be clear, I mean the bug/diagnostic is that it fell back to () versus telling you about !'s limitations; ! implementing all traits is problematic.)

Here's a (closed) issue for this case in particular.

2 Likes

Interesting. At least it's a known bug.