Better unused variable warning

3e08d11
Opened by leonardo-m at 2024-12-21 04:50:15

Given the code:

fn main() {
    let best = [1, 2, 3]
              .iter()
              .enumerate()
              .min_by_key(|&(i, f)| f);

    println!("{:?}", best);
}

The last Nighly rustc gives the warning:

warning: unused variable: `i`
--> ...\test.rs:5:31
  |
5 |                .min_by_key(|&(i, f)| f);
  |                              ^ help: consider using `_i` instead
  |
  = note: #[warn(unused_variables)] on by default

But I think it's better to suggest the programmer to use write _ instead of _i.

  1. It depends a bit on context, there have been cases where I purposely left the variable name prepended with _ to provide context to other programmers about what is being ignored. That being said, I could see how single letter variables would normally not be that important to keep. Should we check the length of the unused variable's name to see if it is, lets say, longer shorter than 2 and if it is suggest replacing with _?

    Esteban Kuber at 2018-03-06 21:33:29

  2. In my opinion if a programmer writes:

    .min_by_key(|&(_i, f)| f);

    Then there's no need for a warning. So if you want to leave an underscore with a name as you say, it's OK.

    But if the leading underscore is missing, and that variable is unused, then most times I don't want to leave a name, I prefer just an underscore. To better show that part of information is unused. That warning has allowed me sometimes to avoid bugs because I forgot to use one of lambda arguments inside the lambda... Generally rustc warnings allow me to catch many bugs, like when I am not using all the information I am supposed to use in an algorithm...

    This is a personal taste of mine, if you think the current design is OK, then we can close this issue down, it's not important :-) And the current warning is enough to catch my bugs I noted above.

    leonardo-m at 2018-03-06 22:59:42

  3. Another case where suggesting "_" is better than suggesting "_i":

    fn main() {
        for i in 0 .. 10 {}
    }
    
    warning: unused variable: `i`
     --> ...\test.rs:2:9
      |
    2 |     for i in 0 .. 10 {}
      |         ^ help: consider using `_i` instead
      |
      = note: #[warn(unused_variables)] on by d
    ```efault
    

    leonardo-m at 2018-03-19 18:55:56