It would be great to have a uabs or unsigned_abs (or something else, the name isn't important) method that returns the absolute value of the given signed integer as an unsigned integer of the same size. (e.g. uabs(self: i8) -> u8)
Advantages
- It encodes the guarantee that the result is positive.
- It is more concise and less error-prone than workarounds
Disadvantages
Implementation
impl iX {
pub fn uabs(self) -> uX {
self.wrapping_abs() as uX
}
}
Alternatives
x.abs() as uX
iX::MIN.abs() panics in debug mode
x.wrapping_abs() as uX
if x == iX::MIN { x as uX } else { x.abs() as uX }
- Redefining
iX::abs
- May cause compatibility issues
Related: #1017, rust-lang/rust#2353
It would be great to have a
uabsorunsigned_abs(or something else, the name isn't important) method that returns the absolute value of the given signed integer as an unsigned integer of the same size. (e.g.uabs(self: i8) -> u8)Advantages
Disadvantages
Implementation
Alternatives
x.abs() as uXiX::MIN.abs()panics in debug modex.wrapping_abs() as uXif x == iX::MIN { x as uX } else { x.abs() as uX }iX::absRelated: #1017, rust-lang/rust#2353