Description
Ambiguous integer or float type variable can lead to some rather confusing error messages. Consider:
fn main() {
println!("{:?}", 2.0.powi(2));
println!("{:?}", 2.0 as u32);
}
Method calls on an ambiguous number type
The first error says that {float}
doesn't have a method called powi
, but taken naively that's not true: both f32
and f64
have methods powi
. The actual problem is that the type inference doesn't know which floating point type the user wants.
The help
is even more confusing, because it suggests the user to use a deprecated trait that's not even documented anymore.
rustc 1.18.0-nightly (5c94997b6 2017-03-30)
error: no method named `powi` found for type `{float}` in the current scope
--> <anon>:2:26
|
2 | println!("{:?}", 2.0.powi(2));
| ^^^^
|
= help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
= help: candidate #1: `use core::num::Float;`
Casting an ambiguous number type
Likewise, when casting one could again run into the same problem. Here, it complains that the cast is "non-scalar" but naively {float}
sounds like a perfectly scalar type! In reality the problem is that casting requires the source type to be non-ambiguous.
error: non-scalar cast: `{float}` as `u32`
--> <anon>:3:22
|
3 | println!("{:?}", 2.0 as u32);
| ^^^^^^^^^^
error: aborting due to 2 previous errors
Suggestion
Tentative PR: master...Rufflewind:ambiguous-number-type
Tweak the error messages a bit when the type is {float}
or {integer}
. Also, perhaps suggestions for deprecated traits could be suppressed?
rustc 1.18.0-nightly (5c94997b6 2017-03-30)
error: no method named `powi` found for the ambiguous type `{float}` in the current scope
--> <anon>:2:26
|
2 | println!("{:?}", 2.0.powi(2));
| ^^^^
|
= help: if you meant to call the `powi` method of, say, `f64`, consider adding some type annotations to clarify that `{float}` should be `f64`
error: casting from an ambiguous type: `{float}` as `u32`
--> <anon>:3:22
|
3 | println!("{:?}", 2.0 as u32);
| ^^^^^^^^^^
error: aborting due to 2 previous errors