{

How to disable unused code warnings in Rust example


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

For example,

You declared an 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, variable declared, but never used.

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

It throws an 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 compile and running the code.

How to disabled unused code warning in Rust?

There are multiple ways to fix an unused code warnings.

First, using allow attribute in code for function structs, 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 below code at starting in the rust code file.

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

So below code does not throws 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 rust compiler using -A

rustc -A dead_code hello.rs

Third way, adding underscore(_) to names of variables, functions,structs.

Below code disables warnings by adding _to an variable.

fn main() {
    let _str = "Hello John";
    println!("Hello World")
}
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.