Why i32::abs from stdlib so strange function?

I need absolute value of i32, there is stdlib function for that,
but it looks really strange:

pub const fn abs(self) -> i32

Because of it return i32, it obviously can panic, as stated in its description.

The absolute value of i32::min_value() cannot be represented as an i32, and attempting to calculate it will cause an overflow. This means that code in debug mode will trigger a panic on this case

There are also checked_abs, overflow_abs, wrapping_abs,
but all of them return strange thing,
why there is no i32::abs that just return u32 ?


I'm not familiar with the reasons behind this, but you can do this: i64::from(value).abs() as u32

The TL;DR of it is that it's because that's how the system abs is specified.

If I'm not mistaken, however, you can get the -> u32 version by literally just doing i32.wrapping_abs() as u32, because i32::MIN and u32::MAX / 2 + 1 have the same bit representation.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.