How to disable unused code warnings in Rust example

In Rust code, Sometimes, You declared a variable or type or defined something, But never used it in the code, It throws an error.

For example,

You declared a struct, but never constructed with fields

struct Employee;

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

Running the above program throws 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 see another example In this example, the variable is declared but never used.

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

It 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

So all these warnings are thrown during compiling and running the code.

How to disable unused code warnings in Rust?

There are multiple ways to fix an unused code warning.

First, use the allow attribute in code for function structs, and objects.

Add #[allow(dead_code)] 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

So for unused_variables errors, you can add #![allow(unused_variables)].

To avoid warnings in code, You have to add the below code at starting in the rust code file.

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

So below code does not throw a warning

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

Second way, using 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, adding underscore(_) to the names of variables, functions, and structs.

The below code disables warnings by adding _to a variable.

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