John Behan - Senior Software Developer

John Behan

Senior Software Developer & Mentor

Warnings and errors are good. We want to be told when we're doing something wrong or something with the potential to cause problems in the future. But sometimes it's ok to turn off those warnings.

Turning off a warning in Rust at the code level

fn main() {
  let mut my_variable = 'foo';
  my_variable = 'bar';
}

If we try to compile this block of code we will see this warning -

warning: variable my_variable is assigned to, but never used

By adding #[allow(unused_variables)] above the variable declaration we can suppress this warning

But there is another warning -

warning: value assigned to my_variable is never read

We can suppress this warning by adding #[allow(unused_assignments)] above the line that reassigns my_variable. Or…

If we add #[allow(unused_variables, unused_assignments)] above the function. Our code now looks like this and gives no warnings when compiled.

#[allow(unused_variables, unused_assignments)]
fn main() {
  let mut my_variable = "foo";
  my_variable = "bar";
}

Suppressing warnings when developing can be useful as it reduces the amount of noise we need to filter out when we're trying something out or debugging. But it is important to turn these warnings back on and to address any underlying issues once our code is ready.