Reputation: 6587
Is there a way to get a negative number with binary assignment without the warning while preserving the other, more valid warnings. Or am I thinking about this wrong?
const NEG: i32 = 0b1000_0000_0000_0000_0000_0000_0000_0000;
// -2147483648
warning: literal out of range for i32
--> src/main.rs:1:18
|
1 | const NEG: i32 = 0b1000_0000_0000_0000_0000_0000_0000_0000;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: #[warn(overflowing_literals)] on by default
Upvotes: 3
Views: 700
Reputation: 164689
Or am I thinking about this wrong?
If all you want is the minimum and maximum i32
, there's already MIN
and MAX
constants in the std::i32
module. They're easier to understand, and you can't make a mistake.
use std::i32;
fn main() {
const POS: i32 = i32::MAX;
const NEG: i32 = i32::MIN;
println!("{} {}", NEG, POS);
}
Upvotes: 1
Reputation: 430574
You can start with an unsigned type and then cast to a signed:
const NEG: i32 = 0b1000_0000_0000_0000_0000_0000_0000_0000_u32 as i32;
without the warning while preserving the other, more valid warnings
You can disable specific warnings for specific expressions:
#[allow(overflowing_literals)]
const NEG: i32 = 0b1000_0000_0000_0000_0000_0000_0000_0000;
However, this original behavior seems incorrect. The binary value is not out of range of an i32
. An issue seems to exist.
Upvotes: 6
Reputation: 8466
You can place a -
in front of it:
// warning
const N1: i32 = 0b1000_0000_0000_0000_0000_0000_0000_0000;
// no warning
const N2: i32 = -0b1000_0000_0000_0000_0000_0000_0000_0000;
assert_eq!(N1, N2);
However, your case is a special case, since -N1 == N2
. Otherwise you have to negate one result of course (otherwise it would be super unintuitive).
Upvotes: 1