I saw a question talk about this:
let i = (-100).abs();
error[E0689]: can't call method `abs` on ambiguous numeric type `{integer}`
And from a post:
{integer} is how rustc prints out the placeholder type for an integer literal. It's not a real type; it needs to collapse to a real iN or uN type to be used.
I think (-100)
should be able to inferred or collapse as (-100_i32)
automatically.
The following code shows it is possible to achieve the desired behavior if abs
is a trait method impl directly on i32
, i16
, etc.
fn main() {
let num1 = (-100).foo_abs(); // num1: i32
let num2 = (-100_i16).foo_abs(); // num2: i16
}
trait FooAbs {
fn foo_abs(self) -> Self;
}
impl FooAbs for i16 {
fn foo_abs(self) -> Self {
if self.is_positive() {
self
} else {
-self
}
}
}
impl FooAbs for i32 {
fn foo_abs(self) -> Self {
if self.is_positive() {
self
} else {
-self
}
}
}
Is there any reason or benefit behind the current design, or is it not implemented in this way for a specific purpose?