How do I get an absolute value in Rust?

瘦欲@ 提交于 2020-03-13 07:00:11

问题


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); dunno what version. I didn't realize those docs were so outdated. oO

Current docs seem to indicate there is no such function?


回答1:


Nowadays, abs is a method on most number types.

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



回答2:


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

Instead, use:

i32::abs(n)



回答3:


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. :|




回答4:


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 .



来源:https://stackoverflow.com/questions/27182808/how-do-i-get-an-absolute-value-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!