In this elementary Rust program a function calculates the absolute value of an integer, and main() helps in completing a statement with the result:
fn main() {
let value = abs(-4);
println!("{}.", value);
}
fn abs(x: i32) -> i32 {
print!("The abs value of {} is ", x);
if x > 0 {
return x;
} else {
-x
}
}
Is there a way to print correctly the whole statement "The abs value of... is..." into the abs() function? I tried unsuccessfully with
println!("The abs value of {} is {} ", x, x);
This always prints the value of the x parameter (e.g. -4, -4) so it's not correct.
And with
println!("The abs value of {} is {} ", x, abs(x));
But here, for some reason, Rust is not happy with recursion, gives a warning at compilation and then doesn't run the program.
Try this to avoid recursion:
Output:
There are built-in
.abs()
method for primitive types e.g. i8, i16, i32, i64, i128, f32, and f64:Overflow behavior
The following code, will panic in debug mode (and returns
-128
in release mode):Since
abs(-2_147_483_648_i32)
is2_147_483_648_u32
, you may returnu32
instead ofi32
:Output: