How to disable warning for single statement in Rust?

Let's say there is one warning, such as path_statements , unused_variables . Is there a way to ignore one moment of this without isolating them from a code block or function?

To be clear when there is one warning in the code. I would like it to be quiet, but there was no need to make special changes regarding a specific warning. And without these reassuring warnings somewhere else, even later in the same function.

With GCC, this can be done as follows:

 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat" /* Isolated region which doesn't raise warnings! */ this_would_raise_Wformat(args); #pragma GCC diagnostic pop 

Does Rust have an equivalent capability?


Notice I am asking about the general case, like silent warnings. I know there are ways to resolve an unused var warning, for example.

+5
source share
2 answers

To disable warnings, you need to add the allow(warning_type) attribute to the affected expression or to any of its parents. If you only want to disable the warning on one particular expression, you can theoretically add an attribute to that / statement expression:

 fn main() { #[allow(unused_variables)] let not_used = 27; #[allow(path_statements)] std::io::stdin; println!("hi!"); } 

However, this feature is experimental and only available at night ! You can read the current discussion about this feature here .


At the same time, you have several different options:

  • Add an attribute to the parent scope (e.g., function). It also silences other warnings. You can also use internal attributes (for example, #![allow(unused_variables)] ) that apply to the entire scope. If you use the internal attribute at the top of the module file, it will apply to the entire file.
  • In the case of unused_variables you can run the variable name with an underline to turn off the warning. Therefore let _not_used = 27; will not trigger a warning.
  • In (at least) some path_statements cases path_statements you can add let _ = on the right side of the path statement to turn off the warning.
+10
source

I'm not sure if this is what you need, but if you want to disable all warnings in the module, write for example. #![allow(dead_code)] (check the exclamation mark) at the top of the module. This will disable all warnings of this type throughout the module. You can also call rustc , for example. -A dead_code .

Edit : you can turn off all warnings by writing #![allow(warnings)] at the top of the module.

Edit2 : you can insert mod ule (as described in the Rust book ) where specific warnings are ignored.

Edit3 : as Lucas said, you can also write, for example. #[allow(dead_code)] in the expression or expression, but currently experimental .

+1
source

All Articles