How do I get an absolute value in Rust?

The docs are unhelpful: http://web.mit.edu/rust-lang_v0.9/doc/std/num/fn.abs.html

Obviously, I can see the function right there, but I haven't got the faintest idea how to call it.

Edit:

The problem is that it doesn't work. :)

use std::num;
let x = num::abs(value);

"Unresolved name: num::abs"

Edit 2: running the nightly from yesterday (11/26/2014); I don't know what version. I didn't realize those docs were so outdated. oO

Current docs seem to indicate there is no such function?

56656 次浏览

That's because you are probably not providing enough type information .

fn main() {
println!("Abs is \"{}\"",
std::num::abs(-42i));
}

notice the i suffix that tells to Rust that -42 is an integer .

Rule of the thumb is that: you have to specify what your type is somewhere, somehow and the suffix are handy, for example another way this works is

fn main() {
let x = -42i;
println!("Abs is \"{}\"",
std::num::abs(x));
}

this works too

fn main() {
let x: int = -42;
println!("Abs is \"{}\"",
std::num::abs(x));
}

if you want a mutable you just have to add mut right after let

fn main() {
let mut x: int = -42;
x += x;
println!("Abs is \"{}\"",
std::num::abs(x));
}

and you get x and you can change the value of x .

Never managed to make rustc recognize abs as a function. I finally went with:

let abs = if val < 0 {
abs * -1
} else {
abs
};

Could have started that way to begin with, I guess, but I'm still trying to learn the libraries. :|

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.

In order for abs() to work, it should already know the type of the value. If you notice in the above answers, context already determines the type of number. However, this will not work:

println!("{}", (-1).abs());

It will give error:

 can't call method `abs` on ambiguous numeric type

Because Rust wants to know exactly which integer type a value has before it calls the type’s own methods. In this case, you should

println!("{}", (-1_i32).abs());
println!("{}", i32::abs(-1));
pub fn absolute_value(&self) -> i16 {
i16::abs(self.0) + i16::abs(self.1)
}