Skip to content

Bad "Ambiguous Numeric Type" Recommendation from Compiler in for loop #53572

Open
@spwitt

Description

@spwitt

The pow function cannot be called on an ambiguous numeric type. If pow is called on the variable of a for loop, the compiler's recommended solution to add a concrete numeric type does not compile.

Example code with ambiguous numeric type:

pub fn check() {
    for i in 0..1000 {
        println!("{}", i.pow(2));
    }
}

Gives the error:

error[E0689]: can't call method `pow` on ambiguous numeric type `{integer}`
  --> src/lib.rs:22:26
   |
22 |         println!("{}", i.pow(2));
   |                          ^^^
help: you must specify a type for this binding, like `i32`
   |
21 |     for i: i32 in 0..1000 {
   |         ^^^^^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0689`

Implementing this recommendation by adding type to variable i as shown in the compiler recommendation and trying to compile again gives the error:

error: missing `in` in `for` loop
  --> src/lib.rs:21:10
   |
21 |     for i: i32 in 0..1000 {
   |          ^ help: try adding `in` here

error: expected expression, found `:`
  --> src/lib.rs:21:10
   |
21 |     for i: i32 in 0..1000 {
   |          ^ expected expression

error: aborting due to 2 previous errors

Not sure if there is a better solution, but adding a cast to the range rather than specifying the type of the variable worked for me:

pub fn check() {
    for i in 0..1000 as i32 {
        println!("{}", i.pow(2));
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions