Irrelevant(?) code causes `type annotations needed` error

Hi,

I have a strange problem and I'm not sure what exactly is wrong here. The compiler gives an error at 2_u8 as _ saying that type annotations are needed.

fn main() {
    // Delete the following line to get rid of the error
    let a: String = serde_yaml::from_str("").unwrap();

    if 1_u16 == 2_u8 as _ { // Error: type annotations needed (E0282)
        println!("???");
    }
}
--> src/main.rs:5:25
  |
5 |     if 1_u16 == 2_u8 as _ { // Error: type annotations needed (E0282)
  |                         ^ cannot infer type

The strange thing is that if I remove the first line, the error disappears. But I can't see how they are related. This looks like a compiler bug to me but still, I'm not sure. What should be done here?

[package]
name = "project"
authors = ["x"]
version = "0.1.0"
edition = "2021"

[dependencies]
# At least using version 0.9.2 eliminates the error
serde_yaml = "0.8.26"

That is pretty weird. My guess is that mentioning serde_yaml somehow makes it register that crates' PartialEq implementations which then somehow trip up inference (even though that shouldn't effect casting). E.g. maybe one part of the compiler asks another to figure out the type of the RHS of == before considering that the RHS is a cast (which would limit the viable types).

I'd go ahead and file an issue.

1 Like

Of course it can affect casting. Here's the trivial example:

trait X { }

impl X for u8 { }

impl PartialEq<dyn X> for u16 {
    fn eq(&self, _: &dyn X) -> bool {
        true
    }
}

fn main() {
    if 1_u16 == 2_u8 as _ { // Error: type annotations needed (E0282)
        println!("???");
    }
}

Not sure that's what happens with Serde, but I would try to look there first before looking on the compiler.

2 Likes

Yeah, you're completely right. The poor error message threw my thinking off.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.