Can't call method `sqrt` on ambiguous numeric type `{integer}`

Given this code

fn main() {
    let x = 16;
    println!("{}", x.sqrt());
}

I get an error:

Compiling sqrt v0.1.0 (/home/gabor/work/rust.code-maven.com/slides/rust/examples/numbers/sqrt)
error[E0689]: can't call method sqrt on ambiguous numeric type {integer}
--> src/main.rs:3:22
|
3 | println!("{}", x.sqrt());
| ^^^^
|
help: you must specify a type for this binding, like i32
|
2 | let x: i32 = 16;
| +++++

For more information about this error, try rustc --explain E0689.
error: could not compile sqrt (bin "sqrt") due to 1 previous error


Following the suggestion I try:

```rust
fn main() {
    let x: i32 = 16;
    println!("{}", x.sqrt());
}

and get this error:

   Compiling sqrt v0.1.0 (/home/gabor/work/rust.code-maven.com/slides/rust/examples/numbers/sqrt)
error[E0599]: no method named `sqrt` found for type `i32` in the current scope
 --> src/main.rs:8:22
  |
8 |     println!("{}", x.sqrt());
  |                      ^^^^ method not found in `i32`

For more information about this error, try `rustc --explain E0599`.
error: could not compile `sqrt` (bin "sqrt") due to 1 previous error

I need to convert the number into floating point for the sqrt to work.

fn main() {
    let x: i32 = 16;
    let x_square = (x as f32).sqrt();
    println!("The square of {x} is {x_square}");
}

Wouldn't it be possible for the first suggestion to not recommend an incorrect solution?

It's not that it's telling you that you can call sqrt if you specify the binding as being i32, it's saying that you can't call any methods (of which sqrt is merely one pertinent example) on an ambiguous type.

That said, it probably should be reworded to avoid implying that adding the type constraint will help the specific code work.

2 Likes