How to deny int variable without explicit type annotation in Rust?

Viewed 161

I often use integer type without type annotation:

let mut counter = 0

If there is no constraint, rustc will infer x is a i32. (rfcs/0212-restore-int-fallback.md at master · rust-lang/rfcs).

Sometimes it causes a problem: overflowing.

for _ in 0..1_000_000_000_000usize {
    counter += 1; # overflow!
    ...
}

So I want to tell rustc to deny integer variable without explicit type annotation:

let mut counter = 0; # Deny
let mut counter: u64 = 0; # OK, because `counter` is explicitly annotated with `u64`

How to do this?

1 Answers

There is a new lint default_numeric_fallback:

#[warn(clippy::default_numeric_fallback)]

pub fn is_yelled(s: &str) -> bool {
    let (n_upper, n_lower) = s.chars().fold((0, 0), |(n_upper, n_lower), c| {
        if c.is_uppercase() {
            (n_upper + 1, n_lower)
        } else if c.is_lowercase() {
            (n_upper, n_lower + 1)
        } else {
            (n_upper, n_lower)
        }
    });
    
    n_upper > n_lower
}

will output:

warning: default numeric fallback might occur
 --> src/lib.rs:4:46
  |
4 |     let (n_upper, n_lower) = s.chars().fold((0, 0), |(n_upper, n_lower), c| {
  |                                              ^ help: consider adding suffix: `0_i32`
  |
note: the lint level is defined here
 --> src/lib.rs:1:8
  |
1 | #[warn(clippy::default_numeric_fallback)]
  |        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#default_numeric_fallback

warning: default numeric fallback might occur
 --> src/lib.rs:4:49
  |
4 |     let (n_upper, n_lower) = s.chars().fold((0, 0), |(n_upper, n_lower), c| {
  |                                                 ^ help: consider adding suffix: `0_i32`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#default_numeric_fallback

warning: default numeric fallback might occur
 --> src/lib.rs:6:24
  |
6 |             (n_upper + 1, n_lower)
  |                        ^ help: consider adding suffix: `1_i32`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#default_numeric_fallback

warning: default numeric fallback might occur
 --> src/lib.rs:8:33
  |
8 |             (n_upper, n_lower + 1)
  |                                 ^ help: consider adding suffix: `1_i32`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#default_numeric_fallback

Unfortunately the lint is not warn for now but only in pedantic list. And it's strange to suggest i32 as default. For example, this code sample should use usize.

Source: https://github.com/rust-lang/rust-clippy/issues/6064

Related