Rust-clippy: Suggest saturating_sub for if i != 0 { i -= 1; }

Created on 1 Apr 2020  路  3Comments  路  Source: rust-lang/rust-clippy

#![warn(clippy::all)]

fn main() {
    let end = 10;
    let start = 5;

    let mut i = end - start;

    if i != 0 {
        i -= 1;
    }

    println!("i: {}", i);
}

could be optimized to

#![warn(clippy::all)]

fn main() {
    let end = 10;
    let start = 5;

    let mut i = (end - start).saturating_sub(1);

    println!("i: {}", i);
}
A-style A-suggestion L-lint

Most helpful comment

Never written a lint before. Could I take a shot at this?

All 3 comments

The example is only correct for unsigned types. But this could also be implemented for signed types.

Never written a lint before. Could I take a shot at this?

Yeah, sure! Here's a document on how to get started writing new lints: https://github.com/rust-lang/rust-clippy/blob/master/doc/adding_lints.md. I you have any questions, just ask here or open a WIP PR.

Was this page helpful?
0 / 5 - 0 ratings