'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?
Solution 1:[1]
The answer mentioning std::num::abs doesn't work anymore.
Instead, use:
i32::abs(n)
Solution 2:[2]
fn main() {
let mut number: i32 = -8;
number = number.abs();
println!("{}", number);
}
Remember that you must specify the datatype explicitly.
Solution 3:[3]
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));
Solution 4:[4]
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. :|
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nz_21 |
| Solution 2 | de-russification |
| Solution 3 | Yilmaz |
| Solution 4 |
