Code Linting in Rust

Rustc provides us with the lints (code checks) feature, which is an important part of the Rust compiler used to detect potential issues in the code.

Lint Levels

Initially, there were four levels, which were later expanded to include <span>expect</span> and <span>force-warn</span>:

Level Meaning Compilation Behavior Overridable Introduced Version
<span>allow</span> Allow No report Yes 1.0
<span>expect</span> Expect Report but marked as expected Yes 1.60
<span>warn</span> Warning Report but continue compilation Yes 1.0
<span>force-warn</span> Force Warning Report but continue compilation No 1.51
<span>deny</span> Deny Report error and stop compilation Yes 1.0
<span>forbid</span> Forbid Report error and stop compilation No 1.0

Setting Lint Levels

1. Crate Level Settings

// At the top of lib.rs or main.rs, effective for the entire crate, note `!`
#![deny(missing_docs)]// Deny
#![warn(unused_imports)]// Warn
#![forbid(unsafe_code)]// Forbid unsafe code (non-overridable)

2. Module Level Settings

#[warn(missing_debug_implementations)]
mod my_module {
// All code within this module follows this rule
pub struct Config; // Will warn about missing Debug implementation
}

3. Item Level Settings

#[allow(dead_code)]// Allow dead code only for this function
fn internal_helper() {
// This function may not be used, but will not warn
}

Lint Options

There are many lint items, commonly categorized into: code style related, documentation related, idioms of different versions, etc. For example:

#![deny(
   missing_docs,
   missing_debug_implementations,
   rust_2018_idioms,
   unused_imports,
   dead_code
)]

You can use <span>rustc -W help</span> to see all options.

Overriding Lint Rules

1. Temporarily Disable Rules

#[allow(unused_variables)]// Temporarily allow unused_variables
fn example() {
let unused_var = 42; // Will not warn
}

#[allow(dead_code)]
mod internal {
fn helper() {} // Internal function, allow dead_code
}

2. Specific Rule Overrides

// Allow certain rules for the entire module
#[allow(missing_docs, missing_debug_implementations)]
mod legacy_code {
pub struct OldStruct; // Allow no documentation and Debug
}

// Restore strict checks
#[warn(missing_docs)]
mod new_code {
/// Documentation for the new structure
#[derive(Debug)]
pub struct NewStruct;
}

Lint Groups

Rustc provides predefined Lint Groups, which are collections of related lints that can be configured all at once. For example, <span>warnings</span> includes all warnings, using <span>#![deny(warnings)]</span> can turn all warnings into errors.

Similarly,<span>unused</span> includes all unused checks:

  • unused_imports
  • unused_variables
  • unused_assignments
  • dead_code
  • unused_must_use

You can also use <span>rustc -W help</span> to see all groups.

Configuring Lint in Cargo

After Rust 1.74, you can also configure lints in Cargo:

[lints.rust]
unsafe_code="forbid"
missing_docs="warn"
unused_imports="warn"

Leave a Comment