No longer unused variables

Rust advises me on unsused variables, ok, i rename them to "_var"
Now, later I use this- Rust does not advise me to name it back again.
Is there a reason to that I dont see?

PS: I am new to Rust.

1 Like

There's a clippy lint if you'd like to enable it.

#[warn(clippy::used_underscore_binding)]
fn main() {
    let _silenced = "";
    println!("But I used it: {}", _silenced);
}

Run Clippy from the Tools menu top-right.

10 Likes

I don’t know if this is the best answer, as I am also new to Rust, but I just never follow the advice of the compiler on this. Why? Because if I am experimenting, I know some variables are not used yet, when I compile some code to see if something else works as I expected. Later on the unused variable gets used, and there is no problem.

But I still like the warnings, because sometimes I didn’t use a variable without thinking right. Then the warning is useful, even if the solution the compiler suggests isn’t the solution I want.

2 Likes

The reason is that unused variables are easy to miss (e.g. you remove some piece of code which uses it, or just forget to write it), while it's hard to accidentally use an underscored variable. At the point of use, you need to type it, so you can rename it at this point.

3 Likes

I think the advice only makes sense to apply when you don't ever plan to use a parameter (which is a valid scenario).

The warning just shouldn't fire when the body of the function ends with todo!().

5 Likes

This is how I work. I may put _something in a field name or function parameter name, but I never write an actual usage of it — always rename it immediately.

4 Likes

For me, fixing warnings is the last thing I do (well okay, warnings -> clippy -> fmt, but you get the idea). I know it can be annoying in some IDEs but I would just ignore warnings--and especially this one--until you feel confident that you've finished your immediate task.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.