Why do underscore prefixed variables exist?

Sir Platypus picture Sir Platypus · Jan 20, 2018 · Viewed 11k times · Source

I am learning Rust, and came across the fact that adding an underscore at the beginning of a variable name will make the compiler not warn if it is unused. I am wondering why that feature exists, since unused variables are frowned upon.

Answer

mcarton picture mcarton · Jan 20, 2018

I can see several reasons:

  • You are calling a function that returns a #[must_use] type, but in your specific case, you know you can safely ignore the value. It is possible to use a _ pattern for that (which is not a variable binding, it's a pattern of its own, but this is probably where the underscore prefix convention comes from), but you might want to document why you ignore the value, or what that value is. This is particularly common in tests in my experience.
  • Function parameter: You might have to name a parameter because it's part of your API, but don't actually need to use it. Anonymous parameters were removed in the 2018 edition.
  • Macros. A variable created in a macro may or may not be used later. It would be annoying to not be able to silence warnings in a macro call. In this case there is a convention of doubling the underscores, this is enforced for example by clippy's used_underscore_binding lint.
  • RAII. You might want to have a variable exist for its destructor side effect, but not use it otherwise. It is not possible to use simply _ for this use-case, as _ is not a variable binding and the value would not be dropped at the end of the enclosing block as with variable binding.