Rust: Incorrect overflowing literals error with saturating_sub

Created on 20 Aug 2019  路  3Comments  路  Source: rust-lang/rust

fn main() {
    assert_eq!(i8::min_value(), -128i8);
    println!("{}", -128i8.saturating_sub(-1));
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error: literal out of range for `i8`
 --> src/main.rs:3:21
  |
3 |     println!("{}", -128i8.saturating_sub(-1));
  |                     ^^^^^
  |
  = note: #[deny(overflowing_literals)] on by default

error: aborting due to previous error

error: Could not compile `playground`.

To learn more, run the command again with --verbose.

-128 is not out of range for i8, however the lint claims it is. This doesn't happen when printing a plain -128i8 without .saturating_sub. It also doesn't happen when the -128i8 is passed as arg to .saturating_sub.

A-lint C-enhancement T-compiler

Most helpful comment

I'm not in favor of a general lint to suggest parenthesizing -$lit.method() but adding a hint to the existing overflow lint would be fine.

All 3 comments

Never mind. Operator precedence was confusing. The - gets applied after calling saturating_sub.

Could a hint be emitted? E.g.

help: did you mean (-128i8).saturating_sub(-1)?

I'm not in favor of a general lint to suggest parenthesizing -$lit.method() but adding a hint to the existing overflow lint would be fine.

Was this page helpful?
0 / 5 - 0 ratings