How to disable unused code warnings in Rust example

In Rust code, if you declare a variable, type, or define something but never use it in the code, it throws an error.

For example, you might declare a struct but never construct it with fields

struct Employee;

fn main() {
    println!("Hello World")
}

Running the above program throws a warning: struct is never constructed:

warning: struct is never constructed: `Employee`
 --> code.rs:1:8
  |
1 | struct Employee;
  |        ^^^^^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: 1 warning emitted
Hello World

Let’s consider another example where a variable is declared but never used.

fn main() {
    let str = "Hello John";
    println!("Hello World")
}

This results throws a warning: unused variable:

warning: unused variable: `str`
 --> code.rs:4:9
  |
4 |     let str = "helo";
  |         ^^^ help: if this is intentional, prefix it with an underscore: `_str`
  |
  = note: `#[warn(unused_variables)]` on by default

warning: 1 warning emitted

Hello World

All these warnings are thrown during compilation and running of the code.

How to Disable Unused Code Warnings in Rust?

There are multiple ways to fix unused code warnings:

First, use the allow attribute in code for functions, structs, and objects. Add #[allow(dead_code)] before the dead code.

hello.rs:

#[allow(dead_code)]
struct Employee;

fn main() {
    println!("Hello World")
}

Running the above program disables the warning

Hello World

For unused variable errors, you can add #![allow(unused_variables)].

To avoid warnings in code, add the following code at the start of the Rust code filed.

#![allow(dead_code)]
#![allow(unused_variables)]

So the following code does not throw a warning.

#![allow(dead_code)]
#![allow(unused_variables)]
fn main() {
    let str = "Hello John";
    println!("Hello World")
}

The second way is to use the crate attribute #![attribute{argument}] syntax.

#![allow(dead_code)]

Next, pass this argument(dead_code) to the Rust compiler using -A:

rustc -A dead_code hello.rs

The third way is to add an underscore (_) to the names of variables, functions, and structs.

The following code disables warnings by adding _ to a variable:

fn main() {
    let _str = "Hello John";
    println!("Hello World")
}