We can calculate the absolute value of a number using the abs()
method. We have to specify the numeric type before we call the abs method, for example, if we want a 32-bit signed integer we need to put i32 after the number.
This tutorial will go through how to calculate the absolute value of a numeric value in Rust with code examples.
Example #1: Absolute Value of a Signed Integer
Let’s look at an example where we want to calculate the absolute value of an integer:
fn main() { let num = -4 let abs_num = num.abs(); println!("{}", abs_num); }
In the above code, we define the number and then call the abs() method. Let’s run the code to see what happens:
error[E0689]: can't call method `abs` on ambiguous numeric type `{integer}` --> src/main.rs:3:23 | 3 | let abs_num = num.abs(); | ^^^ | help: you must specify a type for this binding, like `i32` | 2 | let num: i32 = -4; | ~~~~~~~~
The error occurs because we did not define the specific numeric type. We need to put an i32 after the number so that Rust knows the number is a 32-bit signed integer. Let’s look at the revised code:
fn main() { let num = -4i32 let abs_num = num.abs(); println!("{}", abs_num); }
Let’s run the code to see the result:
4
We successfully calculated the absolute value of -4, which is 4
The absolute method abs() is an available method for most numeric types.
Example #2: Absolute Value of a Signed Float
Let’s look at an example where we want to calculate the absolute value of a floating point. We need to put an f32 after the number so that Rust knows the number is a 32-bit signed float.
fn main() { let num = -3.4f32; let abs_num = num.abs(); println!("{}", abs_num); }
Let’s run the code to see the result:
3.4
We successfully calculated the absolute value of -3.4, which is 3.4.
Summary
Congratulations on reading to the end of this tutorial! For further reading on Rust, go to the articles:
- How to Concatenate Strings in Rust
- How to Do Bubble Sort in Rust
- What is the Difference Between iter, into_iter and iter_mut in Rust?
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.