Type inferred by rust-analyzer seems not consistent with rustc

screenshot
The type of i is inferred as i32 by rust-analyzer, but rustc treats it as ambiguous numeric type {integer}.

I know that numeric literals without type suffix in rust have undetermined type which is determined by context, so actually I want to ask two questions:

  1. Is this inconsistency a bug or is it work-as-intended?
  2. Why does rustc not infer the type of i as i32, as in my opinion a numeric literal without suffix and sufficient context would be just treated as having type i32?

Integer defaulting to i32 never applies when you make a method call on it. This is because the method name could refer to anything — even a trait impl that the compiler doesn't yet know should apply because the type is unknown. This is unfortunate in a case like abs() where every integer type in fact has that inherent method, but rustc doesn't have a special case for that.

Even this simple program does not compile:

fn main() {
    1.abs();
}
error[E0689]: can't call method `abs` on ambiguous numeric type `{integer}`
2 Likes

Yes, this is just rust-analyzer defaulting the {integer} to i32 after everything is done. Just like rustc, rust-analyzer can't resolve the abs call because the type of i isn't known at that point (you can tell this by trying to "go to definition" on abs), but the type hints show the results of inference after going through the whole function and applying fallback.

1 Like