This must be incredibly simple... ("absolute value" nightmare)


#1

This is my first post and I hope I’m not doing anything wrong with the forum policy,
Well, nice to meet you all! Here’s my supersmall problem…
I can’t wright this “c code” in rust : for (int i=0;i<(x-abs(x-j));i++){ }
more precisely I don’t get how to use abs.

loving rust so far (well, if I don’t deal with absolute numbers)
thanks a lot!
marco


#2

Try this:

for (int i=0;i<(x-(x-j).abs());i++){ }

The absolute function is:

 std::num::abs( )

You could invoke it explicitly worst case: std::num::abs(x-j)


#3

abs() is a method on the various types. Here’s an example using i32:

fn main() {
    let x = 10i32;
    let j = 18;

    for i in 0..x - (x - j).abs() {
        println!("{}", i);
    }
}

#4

To clear up some possible confusion:

This doesn’t exist. It may have existed pre-1.0.0, but rust no longer has numeric traits in the standard library, so the only forms of abs available are inherent methods. (i.e. defined directly on each type, and not usable in generic contexts)

If you want to call it in free function syntax, you can write e.g. i32::abs(x).


Also, in order to use method syntax (x.abs()) as in @vitalyd’s example, the i32 suffix on his 10i32 is important. If the compiler cannot infer the exact type of an integer value, it will complain Error: Type annotations needed when you try to call the method.


Lastly, here are the i32 docs so you can see all of the other inherent methods available.


#5

yes std::num::abs didn’t work
but the other solutions … they do.
so thanks a lot, really.