Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get an absolute value in Rust?

Tags:

rust

People also ask

How do you convert to absolute value?

Subtract the expected value from the actual value (or the other way round) and get the absolute value of the difference: ABS(A2-B2)

What is i32 rust?

i32 : The 32-bit signed integer type.


Nowadays, abs is a method on most number types.

let value = -42i32;
let x = value.abs();

The answer mentioning std::num::abs doesn't work anymore.

Instead, use:

i32::abs(n)

fn main() {
    let mut number: i32 = -8;
    number = number.abs();
    println!("{}", number);
}

Remember that you must specify the datatype explicitly.