Warn-by-default Lints

These lints are all set to the ‘warn’ level by default.

ambiguous-derive-helpers

The ambiguous_derive_helpers lint detects cases where a derive macro’s helper attribute is the same name as that of a built-in attribute.

Example

#![crate_type = "proc-macro"]
#![deny(ambiguous_derive_helpers)]

use proc_macro::TokenStream;

#[proc_macro_derive(Trait, attributes(ignore))]
pub fn example(input: TokenStream) -> TokenStream {
    TokenStream::new()
}

Produces:

warning: there exists a built-in attribute with the same name
  --> file.rs:5:39
   |
 5 | #[proc_macro_derive(Trait, attributes(ignore))]
   |                                       ^^^^^^
   |
   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
   = note: for more information, see issue #151152 <https://github.com/rust-lang/rust/issues/151152>
   = note: `#[deny(ambiguous_derive_helpers)]` (part of `#[deny(future_incompatible)]`) on by default

Explanation

Attempting to use this helper attribute will throw an error:

#[derive(Trait)]
struct Example {
    #[ignore]
    fields: ()
}

Produces:

error[E0659]: `ignore` is ambiguous
 --> src/lib.rs:5:7
  |
5 |     #[ignore]
  |       ^^^^^^ ambiguous name
  |
  = note: ambiguous because of a name conflict with a builtin attribute
  = note: `ignore` could refer to a built-in attribute
note: `ignore` could also refer to the derive helper attribute defined here
 --> src/lib.rs:3:10
  |
3 | #[derive(Trait)]
  |          ^^^^^

ambiguous-glob-imported-traits

The ambiguous_glob_imported_traits lint reports uses of traits that are imported ambiguously via glob imports. Previously, this was not enforced due to a bug in rustc.

Example

#![deny(ambiguous_glob_imported_traits)]
mod m1 {
   pub trait Foo {
       fn method1(&self) {}
   }
   impl Foo for u8 {}
}
mod m2 {
    pub trait Foo {
        fn method2(&self) {}
    }
    impl Foo for u8 {}
}

mod m3{
    pub struct Foo;
}

fn trait_and_trait() {
    use m1::*;
    use m2::*;
    0u8.method1();
    0u8.method2();
}

fn trait_and_non_trait(){
    use m1::*;
    use m3::*;
    0u8.method1();
}

Explanation

Glob imports can bring multiple items with the same name into scope, creating an ambiguity that name resolution has to resolve somehow. This lint reports two different situations where that happens:

When two or more traits with the same name are glob imported (as in trait_and_trait), one of them becomes the “primary” trait, while the others are shadowed. Methods from the primary trait (e.g. method1) still resolve, but methods from the shadowed trait (e.g. method2) become inaccessible. Ideally none of the ambiguous traits would be usable at all, but this is allowed for backwards compatibility (for now).

When a trait and a non-trait item with the same name are both glob imported (as in trait_and_non_trait), the trait is currently recovered from the ambiguity and treated as in scope, specifically so that this lint can still be reported; method resolution is therefore not affected today. This is only possible because the ambiguity is a lint and not a hard error. Once it becomes one, the trait will no longer be placed into scope.

This is a future-incompatible lint to transition this to a hard error in the future.

ambiguous-glob-reexports

The ambiguous_glob_reexports lint detects cases where names re-exported via globs collide. Downstream users trying to use the same name re-exported from multiple globs will receive a warning pointing out redefinition of the same name.

Example

#![deny(ambiguous_glob_reexports)]
pub mod foo {
    pub type X = u8;
}

pub mod bar {
    pub type Y = u8;
    pub type X = u8;
}

pub use foo::*;
pub use bar::*;


pub fn main() {}

Explanation

This was previously accepted but it could silently break a crate’s downstream users code. For example, if foo::* and bar::* were re-exported before bar::X was added to the re-exports, down stream users could use this_crate::X without problems. However, adding bar::X would cause compilation errors in downstream crates because X is defined multiple times in the same namespace of this_crate.

ambiguous-import-visibilities

The ambiguous_import_visibilities lint detects imports that should report ambiguity errors, but previously didn’t do that due to rustc bugs.

Example

#![deny(unknown_lints)]
#![deny(ambiguous_import_visibilities)]
mod reexport {
    mod m {
        pub struct S {}
    }

    macro_rules! mac {
        () => { use m::S; }
    }

    pub use m::*;
    mac!();

    pub use S as Z; // ambiguous visibility
}

fn main() {
    reexport::Z {};
}

Explanation

Previous versions of Rust compile it successfully because it fetched the glob import’s visibility for pub use S as Z import, and ignored the private use m::S import that appeared later.

This is a future-incompatible lint to transition this to a hard error in the future.

ambiguous-panic-imports

The ambiguous_panic_imports lint detects ambiguous core and std panic imports, but previously didn’t do that due to #[macro_use] prelude macro import.

Example

#![deny(ambiguous_panic_imports)]
#![no_std]

extern crate std;
use std::prelude::v1::*;

fn xx() {
    panic!(); // resolves to core::panic
}

Explanation

Future versions of Rust will no longer accept the ambiguous resolution.

This is a future-incompatible lint to transition this to a hard error in the future.

ambiguous-wide-pointer-comparisons

The ambiguous_wide_pointer_comparisons lint checks comparison of *const/*mut ?Sized as the operands.

Example



let ab = (A, B);
let a = &ab.0 as *const dyn T;
let b = &ab.1 as *const dyn T;

let _ = a == b;

Explanation

The comparison includes metadata which may not be expected.

anonymous-parameters

The anonymous_parameters lint detects anonymous parameters in trait definitions.

Example

#![deny(anonymous_parameters)]
// edition 2015
pub trait Foo {
    fn foo(usize);
}
fn main() {}

Explanation

This syntax is mostly a historical accident, and can be worked around quite easily by adding an _ pattern or a descriptive identifier:

trait Foo {
    fn foo(_: usize);
}

This syntax is now a hard error in the 2018 edition. In the 2015 edition, this lint is “warn” by default. This lint enables the cargo fix tool with the --edition flag to automatically transition old code from the 2015 edition to 2018. The tool will run this lint and automatically apply the suggested fix from the compiler (which is to add _ to each parameter). This provides a completely automated way to update old code for a new edition. See issue #41686 for more details.

array-into-iter

The array_into_iter lint detects calling into_iter on arrays.

Example

[1, 2, 3].into_iter().for_each(|n| { *n; });

Explanation

Since Rust 1.53, arrays implement IntoIterator. However, to avoid breakage, array.into_iter() in Rust 2015 and 2018 code will still behave as (&array).into_iter(), returning an iterator over references, just like in Rust 1.52 and earlier. This only applies to the method call syntax array.into_iter(), not to any other syntax such as for _ in array or IntoIterator::into_iter(array).

asm-sub-register

The asm_sub_register lint detects using only a subset of a register for inline asm inputs.

Example

#[cfg(target_arch="x86_64")]
use std::arch::asm;

fn main() {
    #[cfg(target_arch="x86_64")]
    unsafe {
        asm!("mov {0}, {0}", in(reg) 0i16);
    }
}

This will produce:

warning: formatting may not be suitable for sub-register argument
 --> src/main.rs:7:19
  |
7 |         asm!("mov {0}, {0}", in(reg) 0i16);
  |                   ^^^  ^^^           ---- for this argument
  |
  = note: `#[warn(asm_sub_register)]` on by default
  = help: use the `x` modifier to have the register formatted as `ax`
  = help: or use the `r` modifier to keep the default formatting of `rax`

Explanation

Registers on some architectures can use different names to refer to a subset of the register. By default, the compiler will use the name for the full register size. To explicitly use a subset of the register, you can override the default by using a modifier on the template string operand to specify when subregister to use. This lint is issued if you pass in a value with a smaller data type than the default register size, to alert you of possibly using the incorrect width. To fix this, add the suggested modifier to the template, or cast the value to the correct size.

See register template modifiers in the reference for more details.

async-fn-in-trait

The async_fn_in_trait lint detects use of async fn in the definition of a publicly-reachable trait.

Example

pub trait Trait {
    async fn method(&self);
}

Explanation

When async fn is used in a trait definition, the trait does not promise that the opaque Future returned by the associated function or method will implement any auto traits such as Send. This may be surprising and may make the associated functions or methods on the trait less useful than intended. On traits exposed publicly from a crate, this may affect downstream crates whose authors cannot alter the trait definition.

For example, this code is invalid:

pub trait Trait {
    async fn method(&self) {}
}

fn test<T: Trait>(x: T) {
    fn spawn<T: Send>(_: T) {}
    spawn(x.method()); // Not OK.
}

This lint exists to warn authors of publicly-reachable traits that they may want to consider desugaring the async fn to a normal fn that returns an opaque impl Future<..> + Send type.

For example, instead of:

pub trait Trait {
    async fn method(&self) {}
}

The author of the trait may want to write:

use core::future::Future;
pub trait Trait {
    fn method(&self) -> impl Future<Output = ()> + Send { async {} }
}

This still allows the use of async fn within impls of the trait. However, it also means that the trait will never be compatible with impls where the returned Future of the method does not implement Send.

Conversely, if the trait is used only locally, if it is never used in generic functions, or if it is only used in single-threaded contexts that do not care whether the returned Future implements Send, then the lint may be suppressed.

bad-asm-style

The bad_asm_style lint detects the use of the .intel_syntax and .att_syntax directives.

Example

#[cfg(target_arch="x86_64")]
use std::arch::asm;

fn main() {
    #[cfg(target_arch="x86_64")]
    unsafe {
        asm!(
            ".att_syntax",
            "movq %{0}, %{0}", in(reg) 0usize
        );
    }
}

This will produce:

warning: avoid using `.att_syntax`, prefer using `options(att_syntax)` instead
 --> src/main.rs:8:14
  |
8 |             ".att_syntax",
  |              ^^^^^^^^^^^
  |
  = note: `#[warn(bad_asm_style)]` on by default

Explanation

On x86, asm! uses the intel assembly syntax by default. While this can be switched using assembler directives like .att_syntax, using the att_syntax option is recommended instead because it will also properly prefix register placeholders with % as required by AT&T syntax.

bare-trait-object

The lint bare-trait-object has been renamed to bare-trait-objects.

bare-trait-objects

The bare_trait_objects lint suggests using dyn Trait for trait objects.

Example

trait Trait { }

fn takes_trait_object(_: Box<Trait>) {
}

Explanation

Without the dyn indicator, it can be ambiguous or confusing when reading code as to whether or not you are looking at a trait object. The dyn keyword makes it explicit, and adds a symmetry to contrast with impl Trait.

boxed-slice-into-iter

The boxed_slice_into_iter lint detects calling into_iter on boxed slices.

Example

vec![1, 2, 3].into_boxed_slice().into_iter().for_each(|n| { *n; });

Explanation

Since Rust 1.80.0, boxed slices implement IntoIterator. However, to avoid breakage, boxed_slice.into_iter() in Rust 2015, 2018, and 2021 code will still behave as (&boxed_slice).into_iter(), returning an iterator over references, just like in Rust 1.79.0 and earlier. This only applies to the method call syntax boxed_slice.into_iter(), not to any other syntax such as for _ in boxed_slice or IntoIterator::into_iter(boxed_slice).

break-with-label-and-loop

The break_with_label_and_loop lint detects labeled break expressions with an unlabeled loop as their value expression.

Example

'label: loop {
    break 'label loop { break 42; };
};

Explanation

In Rust, loops can have a label, and break expressions can refer to that label to break out of specific loops (and not necessarily the innermost one). break expressions can also carry a value expression, which can be another loop. A labeled break with an unlabeled loop as its value expression is easy to confuse with an unlabeled break with a labeled loop and is thus discouraged (but allowed for compatibility); use parentheses around the loop expression to silence this warning. Unlabeled break expressions with labeled loops yield a hard error, which can also be silenced by wrapping the expression in parentheses.

c-void-returns

The c_void_returns lint detects the use of core::ffi::c_void as a return type.

Example

use std::ffi::c_void;

unsafe extern "C" {
    fn foo() -> c_void;
}

Explanation

c_void is designed for use through a pointer, equivalent to C’s void* type. It is a mistake to use it directly as a return type, and calling extern functions declared as such may result in undefined behavior. C functions that return void must be declared to return () in Rust (omitting the return type implicitly returns ()).

clashing-extern-declarations

The clashing_extern_declarations lint detects when an extern fn has been declared with the same name but different types.

Example

mod m {
    unsafe extern "C" {
        fn foo();
    }
}

unsafe extern "C" {
    fn foo(_: u32);
}

Explanation

Because two symbols of the same name cannot be resolved to two different functions at link time, and one function cannot possibly have two types, a clashing extern declaration is almost certainly a mistake. Check to make sure that the extern definitions are correct and equivalent, and possibly consider unifying them in one location.

This lint does not run between crates because a project may have dependencies which both rely on the same extern function, but declare it in a different (but valid) way. For example, they may both declare an opaque type for one or more of the arguments (which would end up distinct types), or use types that are valid conversions in the language the extern fn is defined in. In these cases, the compiler can’t say that the clashing declaration is incorrect.

coherence-leak-check

The coherence_leak_check lint detects conflicting implementations of a trait that are only distinguished by the old leak-check code.

Example

trait SomeTrait { }
impl SomeTrait for for<'a> fn(&'a u8) { }
impl<'a> SomeTrait for fn(&'a u8) { }

Explanation

In the past, the compiler would accept trait implementations for identical functions that differed only in where the lifetime binder appeared. Due to a change in the borrow checker implementation to fix several bugs, this is no longer allowed. However, since this affects existing code, this is a future-incompatible lint to transition this to a hard error in the future.

Code relying on this pattern should introduce “newtypes”, like struct Foo(for<'a> fn(&'a u8)).

See issue #56105 for more details.

confusable-idents

The confusable_idents lint detects visually confusable pairs between identifiers.

Example

// Latin Capital Letter E With Caron
pub const Ě: i32 = 1;
// Latin Capital Letter E With Breve
pub const Ĕ: i32 = 2;

Explanation

This lint warns when different identifiers may appear visually similar, which can cause confusion.

The confusable detection algorithm is based on Unicode® Technical Standard #39 Unicode Security Mechanisms Section 4 Confusable Detection. For every distinct identifier X execute the function skeleton(X). If there exist two distinct identifiers X and Y in the same crate where skeleton(X) = skeleton(Y) report it. The compiler uses the same mechanism to check if an identifier is too similar to a keyword.

Note that the set of confusable characters may change over time. Beware that if you “forbid” this lint that existing code may fail in the future.

const-evaluatable-unchecked

The const_evaluatable_unchecked lint detects a generic constant used in a type.

Example

const fn foo<T>() -> usize {
    if size_of::<*mut T>() < 8 { // size of *mut T does not depend on T
        4
    } else {
        8
    }
}

fn test<T>() {
    let _ = [0; foo::<T>()];
}

Explanation

In the 1.43 release, some uses of generic parameters in array repeat expressions were accidentally allowed. This is a future-incompatible lint to transition this to a hard error in the future. See issue #76200 for a more detailed description and possible fixes.

const-item-interior-mutations

The const_item_interior_mutations lint checks for calls which mutates an interior mutable const-item.

Example

use std::sync::Once;

const INIT: Once = Once::new(); // using `INIT` will always create a temporary and
                                // never modify it-self on use, should be a `static`
                                // instead for shared use

fn init() {
    INIT.call_once(|| {
        println!("Once::call_once first call");
    });
    INIT.call_once(|| {                          // this second will also print
        println!("Once::call_once second call"); // as each call to `INIT` creates
    });                                          // new temporary
}

Explanation

Calling a method which mutates an interior mutable type has no effect as const-item are essentially inlined wherever they are used, meaning that they are copied directly into the relevant context when used rendering modification through interior mutability ineffective across usage of that const-item.

The current implementation of this lint only warns on significant std and core interior mutable types, like Once, AtomicI32, … this is done out of prudence to avoid false-positive and may be extended in the future.

const-item-mutation

The const_item_mutation lint detects attempts to mutate a const item.

Example

const FOO: [i32; 1] = [0];

fn main() {
    FOO[0] = 1;
    // This will print "[0]".
    println!("{:?}", FOO);
}

Explanation

Trying to directly mutate a const item is almost always a mistake. What is happening in the example above is that a temporary copy of the const is mutated, but the original const is not. Each time you refer to the const by name (such as FOO in the example above), a separate copy of the value is inlined at that location.

This lint checks for writing directly to a field (FOO.field = some_value) or array entry (FOO[0] = val), or taking a mutable reference to the const item (&mut FOO), including through an autoderef (FOO.some_mut_self_method()).

There are various alternatives depending on what you are trying to accomplish:

dangling-pointers-from-locals

The dangling_pointers_from_locals lint detects getting a pointer to data of a local that will be dropped at the end of the function.

Example

fn f() -> *const u8 {
    let x = 0;
    &x // returns a dangling ptr to `x`
}

Explanation

Returning a pointer from a local value will not prolong its lifetime, which means that the value can be dropped and the allocation freed while the pointer still exists, making the pointer dangling. This is not an error (as far as the type system is concerned) but probably is not what the user intended either.

If you need stronger guarantees, consider using references instead, as they are statically verified by the borrow-checker to never dangle.

dangling-pointers-from-temporaries

The dangling_pointers_from_temporaries lint detects getting a pointer to data of a temporary that will immediately get dropped.

Example

fn gather_and_use(bytes: impl Iterator<Item = u8>) {
    let x: *const u8 = bytes.collect::<Vec<u8>>().as_ptr();
    unsafe { use_data(x) }
}

Explanation

Getting a pointer from a temporary value will not prolong its lifetime, which means that the value can be dropped and the allocation freed while the pointer still exists, making the pointer dangling. This is not an error (as far as the type system is concerned) but probably is not what the user intended either.

If you need stronger guarantees, consider using references instead, as they are statically verified by the borrow-checker to never dangle.

dead-code

The dead_code lint detects unused, unexported items.

Example

fn foo() {}

Explanation

Dead code may signal a mistake or unfinished code. To silence the warning for individual items, prefix the name with an underscore such as _foo. If it was intended to expose the item outside of the crate, consider adding a visibility modifier like pub.

To preserve the numbering of tuple structs with unused fields, change the unused fields to have unit type or use PhantomData.

Otherwise consider removing the unused code.

Limitations

Removing fields that are only used for side-effects and never read will result in behavioral changes. Examples of this include:

For side-effects from dropping field values, this lint should be allowed on those fields. For side-effects from containing field types, PhantomData should be used.

deprecated

The deprecated lint detects use of deprecated items.

Example

#[deprecated]
fn foo() {}

fn bar() {
    foo();
}

Explanation

Items may be marked “deprecated” with the deprecated attribute to indicate that they should no longer be used. Usually the attribute should include a note on what to use instead, or check the documentation.

deprecated-where-clause-location

The deprecated_where_clause_location lint detects when a where clause in front of the equals in an associated type.

Example

trait Trait {
  type Assoc<'a> where Self: 'a;
}

impl Trait for () {
  type Assoc<'a> where Self: 'a = ();
}

Explanation

The preferred location for where clauses on associated types is after the type. However, for most of generic associated types development, it was only accepted before the equals. To provide a transition period and further evaluate this change, both are currently accepted. At some point in the future, this may be disallowed at an edition boundary; but, that is undecided currently.

double-negations

The double_negations lint detects expressions of the form --x.

Example

fn main() {
    let x = 1;
    let _b = --x;
}

Explanation

Negating something twice is usually the same as not negating it at all. However, a double negation in Rust can easily be confused with the prefix decrement operator that exists in many languages derived from C. Use -(-x) if you really wanted to negate the value twice.

To decrement a value, use x -= 1 instead.

drop-bounds

The drop_bounds lint checks for generics with std::ops::Drop as bounds.

Example

fn foo<T: Drop>() {}

Explanation

A generic trait bound of the form T: Drop is most likely misleading and not what the programmer intended (they probably should have used std::mem::needs_drop instead).

Drop bounds do not actually indicate whether a type can be trivially dropped or not, because a composite type containing Drop types does not necessarily implement Drop itself. Naïvely, one might be tempted to write an implementation that assumes that a type can be trivially dropped while also supplying a specialization for T: Drop that actually calls the destructor. However, this breaks down e.g. when T is String, which does not implement Drop itself but contains a Vec, which does implement Drop, so assuming T can be trivially dropped would lead to a memory leak here.

Furthermore, the Drop trait only contains one method, Drop::drop, which may not be called explicitly in user code (E0040), so there is really no use case for using Drop in trait bounds, save perhaps for some obscure corner cases, which can use #[allow(drop_bounds)].

dropping-copy-types

The dropping_copy_types lint checks for calls to std::mem::drop and std::ptr::drop_in_place where the dropped value implements the Copy trait.

Example

let x: i32 = 42; // i32 implements Copy
std::mem::drop(x); // A copy of x is passed to the function, leaving the
                   // original unaffected

Explanation

Calling std::mem::drop does nothing for types that implement Copy, since the value will be copied and moved into the function on invocation.

dropping-references

The dropping_references lint checks for calls to std::mem::drop and std::ptr::drop_in_place where the dropped type is a reference instead of an owned value.

Example

let mut lock_guard = mutex.lock();
std::mem::drop(&lock_guard); // Should have been drop(lock_guard), mutex
// still locked
operation_that_requires_mutex_to_be_unlocked();

Explanation

Calling drop on a reference will only drop the reference itself, which is a no-op. It will not call the drop method (from the Drop trait implementation) on the underlying referenced value, which is likely what was intended.

duplicate-macro-attributes

The duplicate_macro_attributes lint detects when a #[test]-like built-in macro attribute is duplicated on an item. This lint may trigger on bench, cfg_eval, test and test_case.

Example

#[test]
#[test]
fn foo() {}

This will produce:

warning: duplicated attribute
 --> src/lib.rs:2:1
  |
2 | #[test]
  | ^^^^^^^
  |
  = note: `#[warn(duplicate_macro_attributes)]` on by default

Explanation

A duplicated attribute may erroneously originate from a copy-paste and the effect of it being duplicated may not be obvious or desirable.

For instance, doubling the #[test] attributes registers the test to be run twice with no change to its environment.

dyn-drop

The dyn_drop lint checks for trait objects with std::ops::Drop.

Example

fn foo(_x: Box<dyn Drop>) {}

Explanation

A trait object bound of the form dyn Drop is most likely misleading and not what the programmer intended.

Drop bounds do not actually indicate whether a type can be trivially dropped or not, because a composite type containing Drop types does not necessarily implement Drop itself. Naïvely, one might be tempted to write a deferred drop system, to pull cleaning up memory out of a latency-sensitive code path, using dyn Drop trait objects. However, this breaks down e.g. when T is String, which does not implement Drop, but should probably be accepted.

To write a trait object bound that accepts anything, use a placeholder trait with a blanket implementation.

trait Placeholder {}
impl<T> Placeholder for T {}
fn foo(_x: Box<dyn Placeholder>) {}

ellipsis-inclusive-range-patterns

The ellipsis_inclusive_range_patterns lint detects the ... range pattern, which is deprecated.

Example

let x = 123;
match x {
    0...100 => {}
    _ => {}
}

Explanation

The ... range pattern syntax was changed to ..= to avoid potential confusion with the .. range expression. Use the new form instead.

exported-private-dependencies

The exported_private_dependencies lint detects private dependencies that are exposed in a public interface.

Example

pub fn foo() -> Option<some_private_dependency::Thing> {
    None
}

This will produce:

warning: type `bar::Thing` from private dependency 'bar' in public interface
 --> src/lib.rs:3:1
  |
3 | pub fn foo() -> Option<bar::Thing> {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(exported_private_dependencies)]` on by default

Explanation

Dependencies can be marked as “private” to indicate that they are not exposed in the public interface of a crate. This can be used by Cargo to independently resolve those dependencies because it can assume it does not need to unify them with other packages using that same dependency. This lint is an indication of a violation of that contract.

To fix this, avoid exposing the dependency in your public interface. Or, switch the dependency to a public dependency.

Note that support for this is only available on the nightly channel. See RFC 1977 for more details, as well as the Cargo documentation.

float-literal-f32-fallback

The float_literal_f32_fallback lint detects situations where the type of an unsuffixed float literal falls back to f32 instead of f64 to avoid a compilation error. This occurs when there is a trait bound f32: From<T> (or equivalent, such as T: Into<f32>) and the literal is inferred to have the same type as T.

Example

fn foo(x: impl Into<f32>) -> f32 {
    x.into()
}

fn main() {
    dbg!(foo(2.5));
}

Explanation

Rust allows traits that are only implemented for a single floating point type to guide type inference for floating point literals. This used to apply in the case of f32: From<T> (where T was inferred to be the same type as a floating point literal), as the only floating point type impl was f32: From<f32>. However, as Rust is in the process of adding support for f16, there are now two implementations for floating point types: f32: From<f16> and f32: From<f32>. This means that the trait bound f32: From<T> can no longer guide inference for the type of the floating point literal. The default fallback for unsuffixed floating point literals is f64. As f32 does not implement From<f64>, falling back to f64 would cause a compilation error; therefore, the float type fallback has been tempoarily adjusted to fallback to f32 in this scenario.

The lint will automatically provide a machine-applicable suggestion to add a _f32 suffix to the literal, which will fix the problem.

This is a future-incompatible lint to transition this to a hard error in the future. See issue #154024 for more details.

for-loops-over-fallibles

The for_loops_over_fallibles lint checks for for loops over Option or Result values.

Example

let opt = Some(1);
for x in opt { /* ... */}

Explanation

Both Option and Result implement IntoIterator trait, which allows using them in a for loop. for loop over Option or Result will iterate either 0 (if the value is None/Err(_)) or 1 time (if the value is Some(_)/Ok(_)). This is not very useful and is more clearly expressed via if let.

for loop can also be accidentally written with the intention to call a function multiple times, while the function returns Some(_), in these cases while let loop should be used instead.

The “intended” use of IntoIterator implementations for Option and Result is passing them to generic code that expects something implementing IntoIterator. For example using .chain(option) to optionally add a value to an iterator.

forbidden-lint-groups

The forbidden_lint_groups lint detects violations of forbid applied to a lint group. Due to a bug in the compiler, these used to be overlooked entirely. They now generate a warning.

Example

#![forbid(warnings)]
#![warn(bad_style)]

fn main() {}

If your crate is using #![forbid(warnings)], we recommend that you change to #![deny(warnings)].

Explanation

Due to a compiler bug, applying forbid to lint groups previously had no effect. The bug is now fixed but instead of enforcing forbid we issue this future-compatibility warning to avoid breaking existing crates.

forgetting-copy-types

The forgetting_copy_types lint checks for calls to std::mem::forget with a value that derives the Copy trait.

Example

let x: i32 = 42; // i32 implements Copy
std::mem::forget(x); // A copy of x is passed to the function, leaving the
                     // original unaffected

Explanation

Calling std::mem::forget does nothing for types that implement Copy since the value will be copied and moved into the function on invocation.

An alternative, but also valid, explanation is that Copy types do not implement the Drop trait, which means they have no destructors. Without a destructor, there is nothing for std::mem::forget to ignore.

forgetting-references

The forgetting_references lint checks for calls to std::mem::forget with a reference instead of an owned value.

Example

let x = Box::new(1);
std::mem::forget(&x); // Should have been forget(x), x will still be dropped

Explanation

Calling forget on a reference will only forget the reference itself, which is a no-op. It will not forget the underlying referenced value, which is likely what was intended.

function-casts-as-integer

The function_casts_as_integer lint detects cases where a function item is cast to an integer.

Example

fn foo() {}
let x = foo as usize;

Explanation

When casting a function item to an integer, it implicitly creates a function pointer that will in turn be cast to an integer. By making it explicit, it improves readability of the code and prevents bugs.

function-item-references

The function_item_references lint detects function references that are formatted with fmt::Pointer or transmuted.

Example

fn foo() { }

fn main() {
    println!("{:p}", &foo);
}

Explanation

Taking a reference to a function may be mistaken as a way to obtain a pointer to that function. This can give unexpected results when formatting the reference as a pointer or transmuting it. This lint is issued when function references are formatted as pointers, passed as arguments bound by fmt::Pointer or transmuted.

hidden-glob-reexports

The hidden_glob_reexports lint detects cases where glob re-export items are shadowed by private items.

Example

#![deny(hidden_glob_reexports)]

pub mod upstream {
    mod inner { pub struct Foo {}; pub struct Bar {}; }
    pub use self::inner::*;
    struct Foo {} // private item shadows `inner::Foo`
}

// mod downstream {
//     fn test() {
//         let _ = crate::upstream::Foo; // inaccessible
//     }
// }

pub fn main() {}

Explanation

This was previously accepted without any errors or warnings but it could silently break a crate’s downstream user code. If the struct Foo was added, dep::inner::Foo would silently become inaccessible and trigger a “struct Foo is private” visibility error at the downstream use site.

improper-ctypes

The improper_ctypes lint detects incorrect use of types in foreign modules.

Example

unsafe extern "C" {
    static STATIC: String;
}

Explanation

The compiler has several checks to verify that types used in extern blocks are safe and follow certain rules to ensure proper compatibility with the foreign interfaces. This lint is issued when it detects a probable mistake in a definition. The lint usually should provide a description of the issue, along with possibly a hint on how to resolve it.

improper-ctypes-definitions

The improper_ctypes_definitions lint detects incorrect use of extern function definitions.

Example

pub extern "C" fn str_type(p: &str) { }

Explanation

There are many parameter and return types that may be specified in an extern function that are not compatible with the given ABI. This lint is an alert that these types should not be used. The lint usually should provide a description of the issue, along with possibly a hint on how to resolve it.

improper-gpu-kernel-arg

The improper_gpu_kernel_arg lint detects incorrect use of types in gpu-kernel arguments.

Example

#[unsafe(no_mangle)]
extern "gpu-kernel" fn kernel(_: [i32; 10]) {}

This will produce:

warning: passing type `[i32; 10]` to a function with "gpu-kernel" ABI may have unexpected behavior
 --> t.rs:2:34
  |
2 | extern "gpu-kernel" fn kernel(_: [i32; 10]) {}
  |                                  ^^^^^^^^^
  |
  = help: use primitive types and raw pointers to get reliable behavior
  = note: `#[warn(improper_gpu_kernel_arg)]` on by default

Explanation

The compiler has several checks to verify that types used as arguments in gpu-kernel functions follow certain rules to ensure proper compatibility with the foreign interfaces. This lint is issued when it detects a probable mistake in a signature.

incomplete-features

The incomplete_features lint detects unstable features enabled with the feature attribute that may function improperly in some or all cases.

Example

#![feature(generic_const_exprs)]

Explanation

Although it is encouraged for people to experiment with unstable features, some of them are known to be incomplete or faulty. This lint is a signal that the feature has not yet been finished, and you may experience problems with it.

inline-no-sanitize

The inline_no_sanitize lint detects incompatible use of #[inline(always)] and #[sanitize(xyz = "off")].

Example

#![feature(sanitize)]

#[inline(always)]
#[sanitize(address = "off")]
fn x() {}

fn main() {
    x()
}

Explanation

The use of the #[inline(always)] attribute prevents the the #[sanitize(xyz = "off")] attribute from working. Consider temporarily removing inline attribute.

integer-to-ptr-transmutes

The integer_to_ptr_transmutes lint detects integer to pointer transmutes where the resulting pointers are undefined behavior to dereference.

Example

fn foo(a: usize) -> *const u8 {
   unsafe {
       std::mem::transmute::<usize, *const u8>(a)
   }
}

Explanation

Any attempt to use the resulting pointers are undefined behavior as the resulting pointers won’t have any provenance.

Alternatively, std::ptr::with_exposed_provenance should be used, as they do not carry the provenance requirement. If wanting to create pointers without provenance std::ptr::without_provenance should be used instead.

See std::mem::transmute in the reference for more details.

internal-eq-trait-method-impls

The internal_eq_trait_method_impls lint detects manual implementations of Eq::assert_receiver_is_total_eq.

Example

#[derive(PartialEq)]
pub struct Foo;

impl Eq for Foo {
    fn assert_receiver_is_total_eq(&self) {}
}

Explanation

This method existed so that #[derive(Eq)] could check that all fields of a type implement Eq. Other users were never supposed to implement it and it was hidden from documentation.

Unfortunately, it was not explicitly marked as unstable and some people have now mistakenly assumed they had to implement this method.

As the method is never called by the standard library, you can safely remove any implementations of the method and just write impl Eq for Foo {}.

This is a future-incompatible lint to transition this to a hard error in the future. See issue #152336 for more details.

internal-features

The internal_features lint detects unstable features enabled with the feature attribute that are internal to the compiler or standard library.

Example

#![feature(rustc_attrs)]

Explanation

These features are an implementation detail of the compiler and standard library and are not supposed to be used in user code.

invalid-doc-attributes

The invalid_doc_attributes lint detects when the #[doc(...)] is misused.

Example

#![deny(warnings)]

pub mod submodule {
    #![doc(test(no_crate_inject))]
}

Explanation

Previously, incorrect usage of the #[doc(..)] attribute was not being validated. Usually these should be rejected as a hard error, but this lint was introduced to avoid breaking any existing crates which included them.

invalid-from-utf8

The invalid_from_utf8 lint checks for calls to std::str::from_utf8 and std::str::from_utf8_mut with a known invalid UTF-8 value.

Example

std::str::from_utf8(b"Ru\x82st");

Explanation

Trying to create such a str would always return an error as per documentation for std::str::from_utf8 and std::str::from_utf8_mut.

invalid-nan-comparisons

The invalid_nan_comparisons lint checks comparisons with the NAN constants of f16, f32, f64, and f128.

Example

let a = 2.3f32;
if a == f32::NAN {}

Explanation

NaN compares unequal to every floating-point value, including itself. Use the is_nan method to check whether a value is NaN.

invalid-value

The invalid_value lint detects creating a value that is not valid, such as a null reference.

Example

unsafe {
    let x: &'static i32 = std::mem::zeroed();
}

Explanation

In some situations the compiler can detect that the code is creating an invalid value, which should be avoided.

In particular, this lint will check for improper use of mem::zeroed, mem::uninitialized, mem::transmute, and MaybeUninit::assume_init that can cause undefined behavior. The lint should provide extra information to indicate what the problem is and a possible solution.

irrefutable-let-patterns

The irrefutable_let_patterns lint detects irrefutable patterns in if lets, while lets, and if let guards.

Example

if let _ = 123 {
    println!("always runs!");
}

Explanation

There usually isn’t a reason to have an irrefutable pattern in an if let or while let statement, because the pattern will always match successfully. A let or loop statement will suffice. However, when generating code with a macro, forbidding irrefutable patterns would require awkward workarounds in situations where the macro doesn’t know if the pattern is refutable or not. This lint allows macros to accept this form, while alerting for a possibly incorrect use in normal code.

See RFC 2086 for more details.

large-assignments

The large_assignments lint detects when objects of large types are being moved around.

Example

let x = [0; 50000];
let y = x;

produces:

warning: moving a large value
  --> $DIR/move-large.rs:1:3
  let y = x;
          - Copied large value here

Explanation

When using a large type in a plain assignment or in a function argument, idiomatic code can be inefficient. Ideally appropriate optimizations would resolve this, but such optimizations are only done in a best-effort manner. This lint will trigger on all sites of large moves and thus allow the user to resolve them in code.

late-bound-lifetime-arguments

The late_bound_lifetime_arguments lint detects generic lifetime arguments in path segments with late bound lifetime parameters.

Example

struct S;

impl S {
    fn late(self, _: &u8, _: &u8) {}
}

fn main() {
    S.late::<'static>(&0, &0);
}

Explanation

It is not clear how to provide arguments for early-bound lifetime parameters if they are intermixed with late-bound parameters in the same list. For now, providing any explicit arguments will trigger this lint if late-bound parameters are present, so in the future a solution can be adopted without hitting backward compatibility issues. This is a future-incompatible lint to transition this to a hard error in the future. See issue #42868 for more details, along with a description of the difference between early and late-bound parameters.

linker-messages

The linker_messages lint forwards warnings from the linker.

Example

#![warn(linker_messages)]

unsafe extern "C" {
  fn foo();
}
fn main () { unsafe { foo(); } }

On Linux, using gcc -Wl,--warn-unresolved-symbols as a linker, this will produce

warning: linker stderr: rust-lld: undefined symbol: foo
         >>> referenced by rust_out.69edbd30df4ae57d-cgu.0
         >>>               rust_out.rust_out.69edbd30df4ae57d-cgu.0.rcgu.o:(rust_out::main::h3a90094b06757803)
  |
note: the lint level is defined here
 --> warn.rs:1:9
  |
1 | #![warn(linker_messages)]
  |         ^^^^^^^^^^^^^^^
warning: 1 warning emitted

Explanation

Linkers emit platform-specific and program-specific warnings that cannot be predicted in advance by the Rust compiler. Such messages are ignored by default for now. While linker warnings could be very useful they have been ignored for many years by essentially all users, so we need to do a bit more work than just surfacing their text to produce a clear and actionable warning of similar quality to our other diagnostics. See this tracking issue for more details: https://github.com/rust-lang/rust/issues/136096.

malformed-diagnostic-attributes

The malformed_diagnostic_attributes lint detects malformed diagnostic attributes.

Example

#[diagnostic::do_not_recommend(message = "message")]
trait Trait {}

Explanation

It is usually a mistake to use options or syntax that is not supported. Check the spelling, and check the diagnostic attribute listing for the correct name and syntax. Also consider if you are using an old version of the compiler; perhaps the option or syntax is only available in a newer version. See the reference for a list of diagnostic attributes and the syntax of each.

malformed-diagnostic-filters

The malformed_diagnostic_filters lint detects malformed filters in diagnostic attributes.

Example

#![feature(rustc_attrs)]
#![allow(internal_features)]

#[rustc_on_unimplemented(on(invalid, message = "unused"))]
trait Trait {}

Explanation

A rustc_on_unimplemented filter must use a supported flag, a name-value predicate, or the all, any, and not predicate operators. Invalid filters are ignored.

malformed-diagnostic-format-literals

The malformed_diagnostic_format_literals lint detects malformed diagnostic format literals.

Example

#[diagnostic::on_unimplemented(message = "{Self}} does not implement `Trait`")]
trait Trait {}

Explanation

The #[diagnostic::on_unimplemented] attribute accepts string literal values that are similar to format!’s string literal. See the reference for details on what is permitted in this string literal.

map-unit-fn

The map_unit_fn lint checks for Iterator::map receive a callable that returns ().

Example

fn foo(items: &mut Vec<u8>) {
    items.sort();
}

fn main() {
    let mut x: Vec<Vec<u8>> = vec![
        vec![0, 2, 1],
        vec![5, 4, 3],
    ];
    x.iter_mut().map(foo);
}

Explanation

Mapping to () is almost always a mistake.

method-call-on-diverging-infer-var

The method_call_on_diverging_infer_var lint detects situations in which a method is called on a value resulting from a never-to-any coercion, without necessary information to infer a type for it.

Example

fn main() {
    let x = panic!();
    x.clone();
}

Explanation

Rust does not generally allow calling methods on values which do not have a known type, such a result of a never-to-any coercion with no type specified.

To aid with transition of code calling methods on Infallible after changing Infallible to be an alias for !, rustc temporarily allows such calls. This will (once again) become an error in the future.

Thanks to never-to-any coercion you can replace method calls on ! with the use of the ! variable, or an as cast to an explicit type:

- x.clone()
+ x
- result.map(|x| x.convert_error())?;
+ result.map(|x| x as ErrorType)?;

mismatched-lifetime-syntaxes

The mismatched_lifetime_syntaxes lint detects when the same lifetime is referred to by different syntaxes between function arguments and return values.

The three kinds of syntaxes are:

  1. Named lifetimes. These are references (&'a str) or paths (Person<'a>) that use a lifetime with a name, such as 'static or 'a.

  2. Elided lifetimes. These are references with no explicit lifetime (&str), references using the anonymous lifetime (&'_ str), and paths using the anonymous lifetime (Person<'_>).

  3. Hidden lifetimes. These are paths that do not contain any visual indication that it contains a lifetime (Person).

Example

#![deny(mismatched_lifetime_syntaxes)]

pub fn mixing_named_with_elided(v: &'static u8) -> &u8 {
    v
}

struct Person<'a> {
    name: &'a str,
}

pub fn mixing_hidden_with_elided(v: Person) -> Person<'_> {
    v
}

struct Foo;

impl Foo {
    // Lifetime elision results in the output lifetime becoming
    // `'static`, which is not what was intended.
    pub fn get_mut(&'static self, x: &mut u8) -> &mut u8 {
        unsafe { &mut *(x as *mut _) }
    }
}

Explanation

Lifetime elision is useful because it frees you from having to give each lifetime its own name and show the relation of input and output lifetimes for common cases. However, a lifetime that uses inconsistent syntax between related arguments and return values is more confusing.

In certain unsafe code, lifetime elision combined with inconsistent lifetime syntax may result in unsound code.

misplaced-diagnostic-attributes

The misplaced_diagnostic_attributes lint detects wrongly placed diagnostic attributes.

Example

#[diagnostic::do_not_recommend]
struct NotUserFacing;

Explanation

It is usually a mistake to specify a diagnostic attribute on an item it is not meant for. For example, #[diagnostic::do_not_recommend] can only be placed on trait implementations, and does nothing if placed elsewhere. See the reference for a list of diagnostic attributes and their correct positions.

missing-abi

The missing_abi lint detects cases where the ABI is omitted from extern declarations.

Example

#![deny(missing_abi)]

extern fn foo() {}

Explanation

For historic reasons, Rust implicitly selects C as the default ABI for extern declarations. Other ABIs like C-unwind and system have been added since then, and especially with their addition seeing the ABI easily makes code review easier.

missing-gpu-kernel-export-name

The missing_gpu_kernel_export_name lint detects gpu-kernel functions that have a mangled name.

Example

extern "gpu-kernel" fn kernel() { }

This will produce:

warning: function with the "gpu-kernel" ABI has a mangled name
 --> t.rs:1:1
  |
1 | extern "gpu-kernel" fn kernel() {}
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: use `unsafe(no_mangle)` or `unsafe(export_name = "<name>")`
  = note: mangled names make it hard to find the kernel, this is usually not intended
  = note: `#[warn(missing_gpu_kernel_export_name)]` on by default

Explanation

gpu-kernel functions are usually searched by name in the compiled file. A mangled name is usually unintentional as it would need to be searched by the mangled name.

To use an unmangled name for the kernel, either no_mangle or export_name can be used.

// Can be found by the name "kernel"
#[unsafe(no_mangle)]
extern "gpu-kernel" fn kernel() { }

// Can be found by the name "new_name"
#[unsafe(export_name = "new_name")]
extern "gpu-kernel" fn other_kernel() { }

mixed-script-confusables

The mixed_script_confusables lint detects visually confusable characters in identifiers between different scripts.

Example

// The Japanese katakana character エ can be confused with the Han character 工.
const エ: &'static str = "アイウ";

Explanation

This lint warns when characters between different scripts may appear visually similar, which can cause confusion.

If the crate contains other identifiers in the same script that have non-confusable characters, then this lint will not be issued. For example, if the example given above has another identifier with katakana characters (such as let カタカナ = 123;), then this indicates that you are intentionally using katakana, and it will not warn about it.

Note that the set of confusable characters may change over time. Beware that if you “forbid” this lint that existing code may fail in the future.

named-arguments-used-positionally

The named_arguments_used_positionally lint detects cases where named arguments are only used positionally in format strings. This usage is valid but potentially very confusing.

Example

#![deny(named_arguments_used_positionally)]
fn main() {
    let _x = 5;
    println!("{}", _x = 1); // Prints 1, will trigger lint

    println!("{}", _x); // Prints 5, no lint emitted
    println!("{_x}", _x = _x); // Prints 5, no lint emitted
}

Explanation

Rust formatting strings can refer to named arguments by their position, but this usage is potentially confusing. In particular, readers can incorrectly assume that the declaration of named arguments is an assignment (which would produce the unit type). For backwards compatibility, this is not a hard error.

non-camel-case-types

The non_camel_case_types lint detects types, variants, traits and type parameters that don’t have camel case names.

Example

struct my_struct;

Explanation

The preferred style for these identifiers is to use “camel case”, such as MyStruct, where the first letter should not be lowercase, and should not use underscores between letters. Underscores are allowed at the beginning and end of the identifier, as well as between non-letters (such as X86_64).

non-contiguous-range-endpoints

The non_contiguous_range_endpoints lint detects likely off-by-one errors when using exclusive range patterns.

Example

let x = 123u32;
match x {
    0..100 => { println!("small"); }
    101..1000 => { println!("large"); }
    _ => { println!("larger"); }
}

Explanation

It is likely a mistake to have range patterns in a match expression that miss out a single number. Check that the beginning and end values are what you expect, and keep in mind that with ..= the right bound is inclusive, and with .. it is exclusive.

non-fmt-panic

The lint non-fmt-panic has been renamed to non-fmt-panics.

non-fmt-panics

The non_fmt_panics lint detects panic!(..) invocations where the first argument is not a formatting string.

Example

panic!("{}");
panic!(123);

Explanation

In Rust 2018 and earlier, panic!(x) directly uses x as the message. That means that panic!("{}") panics with the message "{}" instead of using it as a formatting string, and panic!(123) will panic with an i32 as message.

Rust 2021 always interprets the first argument as format string.

non-local-definitions

The non_local_definitions lint checks for impl blocks and #[macro_export] macro inside bodies (functions, enum discriminant, …).

Example

#![warn(non_local_definitions)]
trait MyTrait {}
struct MyStruct;

fn foo() {
    impl MyTrait for MyStruct {}
}

Explanation

Creating non-local definitions go against expectation and can create discrepancies in tooling. It should be avoided. It may become deny-by-default in edition 2024 and higher, see the tracking issue https://github.com/rust-lang/rust/issues/120363.

An impl definition is non-local if it is nested inside an item and neither the type nor the trait are at the same nesting level as the impl block.

All nested bodies (functions, enum discriminant, array length, consts) (expect for const _: Ty = { ... } in top-level module, which is still undecided) are checked.

non-shorthand-field-patterns

The non_shorthand_field_patterns lint detects using Struct { x: x } instead of Struct { x } in a pattern.

Example

struct Point {
    x: i32,
    y: i32,
}


fn main() {
    let p = Point {
        x: 5,
        y: 5,
    };

    match p {
        Point { x: x, y: y } => (),
    }
}

Explanation

The preferred style is to avoid the repetition of specifying both the field name and the binding name if both identifiers are the same.

non-snake-case

The non_snake_case lint detects variables, methods, functions, lifetime parameters, named fields and modules that don’t have snake case names.

Example

let MY_VALUE = 5;

Explanation

The preferred style for these identifiers is to use “snake case”, where all the characters are in lowercase, with words separated with a single underscore, such as my_value.

non-upper-case-globals

The non_upper_case_globals lint detects static items that don’t have uppercase identifiers.

Example

static max_points: i32 = 5;

Explanation

The preferred style is for static item names to use all uppercase letters such as MAX_POINTS.

noop-method-call

The noop_method_call lint detects specific calls to noop methods such as a calling <&T as Clone>::clone where T: !Clone.

Example

struct Foo;
let foo = &Foo;
let clone: &Foo = foo.clone();

Explanation

Some method calls are noops meaning that they do nothing. Usually such methods are the result of blanket implementations that happen to create some method invocations that end up not doing anything. For instance, Clone is implemented on all &T, but calling clone on a &T where T does not implement clone, actually doesn’t do anything as references are copy. This lint detects these calls and warns the user about them.

opaque-hidden-inferred-bound

The opaque_hidden_inferred_bound lint detects cases in which nested impl Trait in associated type bounds are not written generally enough to satisfy the bounds of the associated type.

Explanation

This functionality was removed in #97346, but then rolled back in #99860 because it caused regressions.

We plan on reintroducing this as a hard error, but in the meantime, this lint serves to warn and suggest fixes for any use-cases which rely on this behavior.

Example

#![feature(type_alias_impl_trait)]

trait Duh {}

impl Duh for i32 {}

trait Trait {
    type Assoc: Duh;
}

impl<F: Duh> Trait for F {
    type Assoc = F;
}

type Tait = impl Sized;

#[define_opaque(Tait)]
fn test() -> impl Trait<Assoc = Tait> {
    42
}

fn main() {}

In this example, test declares that the associated type Assoc for impl Trait is impl Sized, which does not satisfy the bound Duh on the associated type.

Although the hidden type, i32 does satisfy this bound, we do not consider the return type to be well-formed with this lint. It can be fixed by changing Tait = impl Sized into Tait = impl Sized + Duh.

overlapping-patterns

The lint overlapping-patterns has been renamed to overlapping-range-endpoints.

overlapping-range-endpoints

The overlapping_range_endpoints lint detects match arms that have range patterns that overlap on their endpoints.

Example

let x = 123u8;
match x {
    0..=100 => { println!("small"); }
    100..=255 => { println!("large"); }
}

Explanation

It is likely a mistake to have range patterns in a match expression that overlap in this way. Check that the beginning and end values are what you expect, and keep in mind that with ..= the left and right bounds are inclusive.

partial-stack-protector

The partial_stack_protector lint detects uses of the -Z stack-protector compile flag to build a program that contains crates that are not protected by stack-protector, or protected by a weaker level of it than the crate you are compiling.

Example

rustc -Z stack-protector=all
fn main() {}

This will produce:

warning: your program uses the crate `std`, that is not compiled with `stack-protector=all` enabled
 |
 = note: recompile `std` with `stack-protector=all` enabled, or use `-Z allow-partial-mitigations=stack-protector` to allow creating an artifact that has the mitigation partially enabled
 = help: it is possible to disable `-Z allow-partial-mitigations=stack-protector` via `-Z deny-partial-mitigations=stack-protector`
 = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
 = note: for more information, see issue #154613 <https://github.com/rust-lang/rust/issues/154613>
 = note: `#[warn(partial_stack_protector)]` (part of `#[warn(future_incompatible)]`) on by default

Explanation

Using the -Z stack-protector flag on only part of a compiled object will lead to a compiled program that is not fully protected by stack-protector, which is a security risk. This was previously accepted and used in practice, and is now being phased out. This is a future-incompatible lint to transition this to a hard error in the future. See issue #154613 for more details.

If you intentionally want to use the -Z stack-protector flag for only a part of your compiled program, you can allow it in a future-compatible way using the -Z allow-partial-mitigations=stack-protector flag, which must be passed after the -Z stack-protector flag in the command line, for example:

rustc -Z stack-protector=all -Z allow-partial-mitigations=stack-protector

The order dependency is by design, see the RFC 3855 for details.

path-statements

The path_statements lint detects path statements with no effect.

Example

let x = 42;

x;

Explanation

It is usually a mistake to have a statement that has no effect.

private-bounds

The private_bounds lint detects types in a secondary interface of an item, that are more private than the item itself. Secondary interface of an item consists of bounds on generic parameters and where clauses, including supertraits for trait items.

Example

#![deny(private_bounds)]

struct PrivTy;
pub struct S
    where PrivTy:
{}

Explanation

Having private types or traits in item bounds makes it less clear what interface the item actually provides.

private-interfaces

The private_interfaces lint detects types in a primary interface of an item, that are more private than the item itself. Primary interface of an item is all its interface except for bounds on generic parameters and where clauses.

Example

#![deny(private_interfaces)]
struct SemiPriv;

mod m1 {
    struct Priv;
    impl crate::SemiPriv {
        pub fn f(_: Priv) {}
    }
}

Explanation

Having something private in primary interface guarantees that the item will be unusable from outer modules due to type privacy.

ptr-to-integer-transmute-in-consts

The ptr_to_integer_transmute_in_consts lint detects pointer to integer transmute in const functions and associated constants.

Example

const fn foo(ptr: *const u8) -> usize {
   unsafe {
       std::mem::transmute::<*const u8, usize>(ptr)
   }
}

Explanation

Transmuting pointers to integers in a const context is undefined behavior. Any attempt to use the resulting integer will abort const-evaluation.

But sometimes the compiler might not emit an error for pointer to integer transmutes inside const functions and associated consts because they are evaluated only when referenced. Therefore, this lint serves as an extra layer of defense to prevent any undefined behavior from compiling without any warnings or errors.

See std::mem::transmute in the reference for more details.

recursion-depth-exceeding-limit

The recursion_depth_exceeding_limit lint detects cases where the compiler does not correctly track the recursion depth in obligation evaluation.

Example

rustc -Znext-solver example.rs
#![recursion_limit = "8"]
struct Foo<T> {
   t: T,
   opt_t: Option<T>,
}
fn require_sync<T: Sync>() {}
fn main() {
    require_sync::<Foo<Foo<Foo<Foo<Foo<Foo<()>>>>>>>();
}

This will produces:

error[E0275]: overflow evaluating the requirement `Foo<Foo<Foo<Foo<Foo<Foo<()>>>>>>: Sync`
 --> example.rs:12:20
  |
  |     require_sync::<Foo<Foo<Foo<Foo<Foo<Foo<()>>>>>>>();
  |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: consider increasing the recursion limit by adding a `#![recursion_limit = "16"]` attribute to your crate
note: required by a bound in `require_sync`
 --> example.rs:9:20
  |
  | fn require_sync<T: Sync>() {}
  |                    ^^^^ required by this bound in `require_sync`

Explanation

The compiler uses a recursion limit in obligation evaluation to avoid hangs.

However, the old trait solver sometimes ignores the recursion depth, whereas the new solver correctly tracks it. This reveals cases where overflow should have occurred previously.

This is a future-incompatible lint to transition this to a hard error in the future.

redundant-semicolon

The lint redundant-semicolon has been renamed to redundant-semicolons.

redundant-semicolons

The redundant_semicolons lint detects unnecessary trailing semicolons.

Example

let _ = 123;;

Explanation

Extra semicolons are not needed, and may be removed to avoid confusion and visual clutter.

refining-impl-trait-internal

The refining_impl_trait_internal lint detects impl Trait return types in method signatures that are refined by a trait implementation, meaning the implementation adds information about the return type that is not present in the trait.

Example

#![deny(refining_impl_trait)]

use std::fmt::Display;

trait AsDisplay {
    fn as_display(&self) -> impl Display;
}

impl<'s> AsDisplay for &'s str {
    fn as_display(&self) -> Self {
        *self
    }
}

fn main() {
    // users can observe that the return type of
    // `<&str as AsDisplay>::as_display()` is `&str`.
    let _x: &str = "".as_display();
}

Explanation

Callers of methods for types where the implementation is known are able to observe the types written in the impl signature. This may be intended behavior, but may also lead to implementation details being revealed unintentionally. In particular, it may pose a semver hazard for authors of libraries who do not wish to make stronger guarantees about the types than what is written in the trait signature.

refining_impl_trait is a lint group composed of two lints:

We are seeking feedback on each of these lints; see issue #121718 for more information.

refining-impl-trait-reachable

The refining_impl_trait_reachable lint detects impl Trait return types in method signatures that are refined by a publically reachable trait implementation, meaning the implementation adds information about the return type that is not present in the trait.

Example

#![deny(refining_impl_trait)]

use std::fmt::Display;

pub trait AsDisplay {
    fn as_display(&self) -> impl Display;
}

impl<'s> AsDisplay for &'s str {
    fn as_display(&self) -> Self {
        *self
    }
}

fn main() {
    // users can observe that the return type of
    // `<&str as AsDisplay>::as_display()` is `&str`.
    let _x: &str = "".as_display();
}

Explanation

Callers of methods for types where the implementation is known are able to observe the types written in the impl signature. This may be intended behavior, but may also lead to implementation details being revealed unintentionally. In particular, it may pose a semver hazard for authors of libraries who do not wish to make stronger guarantees about the types than what is written in the trait signature.

refining_impl_trait is a lint group composed of two lints:

We are seeking feedback on each of these lints; see issue #121718 for more information.

renamed-and-removed-lints

The renamed_and_removed_lints lint detects lints that have been renamed or removed.

Example

#![deny(raw_pointer_derive)]

Explanation

To fix this, either remove the lint or use the new name. This can help avoid confusion about lints that are no longer valid, and help maintain consistency for renamed lints.

repeated-reprs

The repeated_reprs lint detects when the same representation is specified more than once in a #[repr(..)] attribute.

Example

#[repr(C)]
#[repr(C)]
enum Foo { A }

Explanation

While some representations may be specified more than once, the compiler will reject repeated uses of some others. For consistency, prefer to only specify the representation once.

repr-c-enums-larger-than-int

The repr_c_enums_larger_than_int lint detects repr(C) enums with discriminant values that do not fit into a C int or unsigned int.

Example

#[repr(C)]
enum E {
    V = 9223372036854775807, // i64::MAX
}

This will produce:

error: `repr(C)` enum discriminant does not fit into C `int` nor into C `unsigned int`
  --> $DIR/repr-c-big-discriminant1.rs:16:5
   |
LL |     A = 9223372036854775807, // i64::MAX
   |     ^
   |
   = note: `repr(C)` enums with big discriminants are non-portable, and their size in Rust might not match their size in C
   = help: use `repr($int_ty)` instead to explicitly set the size of this enum

Explanation

In C, enums with discriminants that do not all fit into an int or all fit into an unsigned int are a portability hazard: such enums are only permitted since C23, and not supported e.g. by MSVC.

Furthermore, Rust interprets the discriminant values of repr(C) enums as expressions of type isize. This makes it impossible to implement the C23 behavior of enums where the enum discriminants have no predefined type and instead the enum uses a type large enough to hold all discriminants.

Therefore, repr(C) enums in Rust require that either all discriminants to fit into a C int or they all fit into an unsigned int.

rtsan-nonblocking-async

The rtsan_nonblocking_async lint detects incompatible use of #[sanitize(realtime = "nonblocking")] on async functions.

Example

#![feature(sanitize)]

#[sanitize(realtime = "nonblocking")]
async fn x() {}

fn main() {
    x();
}

Explanation

The sanitizer only considers the async function body nonblocking. The executor, which runs on every .await point can run non-realtime code, without the sanitizer catching it.

self-constructor-from-outer-item

The self_constructor_from_outer_item lint detects cases where the Self constructor was silently allowed due to a bug in the resolver, and which may produce surprising and unintended behavior.

Using a Self type alias from an outer item was never intended, but was silently allowed. This is deprecated – and is a hard error when the Self type alias references generics that are not in scope.

Example

#![deny(self_constructor_from_outer_item)]

struct S0(usize);

impl S0 {
    fn foo() {
        const C: S0 = Self(0);
        fn bar() -> S0 {
            Self(0)
        }
    }
}

Explanation

The Self type alias should not be reachable because nested items are not associated with the scope of the parameters from the parent item.

semicolon-in-expressions-from-non-local-macros

The semicolon_in_expressions_from_non_local_macros lint detects trailing semicolons in macro bodies when the macro is invoked in expression position. This was previously accepted, but is being phased out. This is similar to the semicolon_in_expressions_from_macros lint, but applies to macros expanded from a different crate.

Example

fn main() {
    let val = match true {
        true => false,
        _ => example_separate_crate::foo!()
    };
}

where the crate example-separate-crate contains:

#[macro_export]
macro_rules! foo {
    () => { true; }
}

produces:

warning: trailing semicolon in macro used in expression position
 --> src/main.rs:4:14
  |
4 |         _ => example_separate_crate::foo!()
  |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
  = note: for more information, see issue #79813 <https://github.com/rust-lang/rust/issues/79813>
  = note: `#[warn(semicolon_in_expressions_from_non_local_macros)]` (part of `#[warn(future_incompatible)]`) on by default
  = note: this warning originates in the macro `example_separate_crate::foo` (in Nightly builds, run with -Z macro-backtrace for more info)

Explanation

Previous, Rust ignored trailing semicolon in a macro body when a macro was invoked in expression position. However, this makes the treatment of semicolons in the language inconsistent, and could lead to unexpected runtime behavior in some circumstances (e.g. if the macro author expects a value to be dropped).

This is a future-incompatible lint to transition this to a hard error in the future. See issue #79813 for more details.

special-module-name

The special_module_name lint detects module declarations for files that have a special meaning.

Example

mod lib;

fn main() {
    lib::run();
}

Explanation

Cargo recognizes lib.rs and main.rs as the root of a library or binary crate, so declaring them as modules will lead to miscompilation of the crate unless configured explicitly.

To access a library from a binary target within the same crate, use your_crate_name:: as the path instead of lib:::

// bar/src/lib.rs
fn run() {
    // ...
}

// bar/src/main.rs
fn main() {
    bar::run();
}

Binary targets cannot be used as libraries and so declaring one as a module is not allowed.

stable-features

The stable_features lint detects a feature attribute that has since been made stable.

Example

#![feature(test_accepted_feature)]
fn main() {}

Explanation

When a feature is stabilized, it is no longer necessary to include a #![feature] attribute for it. To fix, simply remove the #![feature] attribute.

static-mut-ref

The lint static-mut-ref has been renamed to static-mut-refs.

static-mut-refs

The static_mut_refs lint checks for shared or mutable references of mutable static inside unsafe blocks and unsafe functions.

Example

fn main() {
    static mut X: i32 = 23;
    static mut Y: i32 = 24;

    unsafe {
        let y = &X;
        let ref x = X;
        let (x, y) = (&X, &Y);
        foo(&X);
    }
}

unsafe fn _foo() {
    static mut X: i32 = 23;
    static mut Y: i32 = 24;

    let y = &X;
    let ref x = X;
    let (x, y) = (&X, &Y);
    foo(&X);
}

fn foo<'a>(_x: &'a i32) {}

Explanation

Shared or mutable references of mutable static are almost always a mistake and can lead to undefined behavior and various other problems in your code.

This lint is “warn” by default on editions up to 2021, in 2024 is “deny”.

suspicious-double-ref-op

The suspicious_double_ref_op lint checks for usage of .clone()/.borrow()/.deref() on an &&T when T: !Deref/Borrow/Clone, which means the call will return the inner &T, instead of performing the operation on the underlying T and can be confusing.

Example

struct Foo;
let foo = &&Foo;
let clone: &Foo = foo.clone();

Explanation

Since Foo doesn’t implement Clone, running .clone() only dereferences the double reference, instead of cloning the inner type which should be what was intended.

suspicious-runtime-symbol-definitions

The suspicious_runtime_symbol_definitions lint checks the signature of items whose symbol name is a runtime symbol expected by core or std.

Example

#[unsafe(no_mangle)]
pub extern "C" fn strlen(ptr: *mut f32) -> usize { 0 }
// suspicious definition of the `strlen` function
// `ptr` should be `*const std::ffi::c_char`

Explanation

Up-most care is required when defining runtime symbols assumed and used by the standard library. They must follow the C specification, not use any standard-library facility or undefined behavior may occur.

The symbols currently checked are memcpy, memmove, memset, memcmp, bcmp, strlen, as well as the following POSIX symbols: open, read, write close, malloc, realloc, free and exit.

  1. https://doc.rust-lang.org/core/index.html#how-to-use-the-core-library

  2. tail-call-track-caller

    The tail_call_track_caller lint detects usage of become attempting to tail call a function marked with #[track_caller].

    Example

    #![feature(explicit_tail_calls)]
    #![expect(incomplete_features)]
    
    #[track_caller]
    fn f() {}
    
    fn g() {
        become f();
    }
    
    g();
    

    Explanation

    Due to implementation details of tail calls and #[track_caller] attribute, calls to functions marked with #[track_caller] cannot become tail calls. As such using become is no different than a normal call (except for changes in drop order).

    trivial-bounds

    The trivial_bounds lint detects trait bounds that don’t depend on any type parameters.

    Example

    #![feature(trivial_bounds)]
    pub struct A where i32: Copy;
    

    Explanation

    Usually you would not write a trait bound that you know is always true, or never true. However, when using macros, the macro may not know whether or not the constraint would hold or not at the time when generating the code. Currently, the compiler does not alert you if the constraint is always true, and generates an error if it is never true. The trivial_bounds feature changes this to be a warning in both cases, giving macros more freedom and flexibility to generate code, while still providing a signal when writing non-macro code that something is amiss.

    See RFC 2056 for more details. This feature is currently only available on the nightly channel, see tracking issue #48214.

    type-alias-bounds

    The type_alias_bounds lint detects bounds in type aliases.

    Example

    type SendVec<T: Send> = Vec<T>;
    

    Explanation

    Trait and lifetime bounds on generic parameters and in where clauses of type aliases are not checked at usage sites of the type alias. Moreover, they are not thoroughly checked for correctness at their definition site either similar to the aliased type.

    This is a known limitation of the type checker that may be lifted in a future edition. Permitting such bounds in light of this was unintentional.

    While these bounds may have secondary effects such as enabling the use of “shorthand” associated type paths1 and affecting the default trait object lifetime2 of trait object types passed to the type alias, this should not have been allowed until the aforementioned restrictions of the type checker have been lifted.

    Using such bounds is highly discouraged as they are actively misleading.

    tyvar-behind-raw-pointer

    The tyvar_behind_raw_pointer lint detects raw pointer to an inference variable.

    Example

    // edition 2015
    let data = std::ptr::null();
    let _ = &data as *const *const ();
    
    if data.is_null() {}
    

    Explanation

    This kind of inference was previously allowed, but with the future arrival of arbitrary self types, this can introduce ambiguity. To resolve this, use an explicit type instead of relying on type inference.

    This is a future-incompatible lint to transition this to a hard error in the 2018 edition. See issue #46906 for more details. This is currently a hard-error on the 2018 edition, and is “warn” by default in the 2015 edition.

    uncommon-codepoints

    The uncommon_codepoints lint detects uncommon Unicode codepoints in identifiers.

    Example

    const µ: f64 = 0.000001;
    

    Explanation

    This lint warns about using characters which are not commonly used, and may cause visual confusion.

    This lint is triggered by identifiers that contain a codepoint that is not part of the set of “Allowed” codepoints as described by Unicode® Technical Standard #39 Unicode Security Mechanisms Section 3.1 General Security Profile for Identifiers.

    Note that the set of uncommon codepoints may change over time. Beware that if you “forbid” this lint that existing code may fail in the future.

    unconditional-recursion

    The unconditional_recursion lint detects functions that cannot return without calling themselves.

    Example

    fn foo() {
        foo();
    }
    

    Explanation

    It is usually a mistake to have a recursive call that does not have some condition to cause it to terminate. If you really intend to have an infinite loop, using a loop expression is recommended.

    uncovered-param-in-projection

    The uncovered_param_in_projection lint detects a violation of one of Rust’s orphan rules for foreign trait implementations that concerns the use of type parameters inside trait associated type paths (“projections”) whose output may not be a local type that is mistakenly considered to “cover” said parameters which is unsound and which may be rejected by a future version of the compiler.

    Originally reported in #99554.

    Example

    // dependency.rs
    #![crate_type = "lib"]
    
    pub trait Trait<T, U> {}
    
    // dependent.rs
    trait Identity {
        type Output;
    }
    
    impl<T> Identity for T {
        type Output = T;
    }
    
    struct Local;
    
    impl<T> dependency::Trait<Local, T> for <T as Identity>::Output {}
    
    fn main() {}
    

    This will produce:

    warning[E0210]: type parameter `T` must be covered by another type when it appears before the first local type (`Local`)
      --> dependent.rs:11:6
       |
    11 | impl<T> dependency::Trait<Local, T> for <T as Identity>::Output {}
       |      ^ type parameter `T` must be covered by another type when it appears before the first local type (`Local`)
       |
       = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
       = note: for more information, see issue #124559 <https://github.com/rust-lang/rust/issues/124559>
       = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local, and no uncovered type parameters appear before that first local type
       = note: in this case, 'before' refers to the following order: `impl<..> ForeignTrait<T1, ..., Tn> for T0`, where `T0` is the first and `Tn` is the last
       = note: `#[warn(uncovered_param_in_projection)]` on by default
    

    Explanation

    FIXME(fmease): Write explainer.

    unevaluated-default-field-value

    The unevaluated_default_field_value lint detects default field values that don’t get evaluated at the definition site because the corresponding struct or enum has type or const parameters, meaning they only get evaluated when the struct or enum gets constructed using that default (post-monormophization).

    Example

    #![feature(default_field_values)]
    
    struct Struct<const T: u8> {
        field1: u8 = 100 + T, // none of these values will be checked until `Struct` is
        field2: u8 = 100,     // constructed, even if they don't refer to the cont param
    }
    

    Explanation

    Const evaluation requires all values to be known. In the case of default field values, they will get evaluated eagerly, but if there are any type or const parameters, the evaluation of the default will only occur when materializing a value of its owning struct and leaving the field with a default value unspecified. For the example above, if you wrote let _: Struct<180> = Struct { .. };, you would get a const evaluation compile error.

    This inconsistency can be confusing, and surprising, because the fields are sometimes evaluated eagerly.

    unexpected-cfgs

    The unexpected_cfgs lint detects unexpected conditional compilation conditions.

    Example

    rustc --check-cfg 'cfg()'
    
    #[cfg(widnows)]
    fn foo() {}
    

    This will produce:

    warning: unexpected `cfg` condition name: `widnows`
     --> lint_example.rs:1:7
      |
    1 | #[cfg(widnows)]
      |       ^^^^^^^
      |
      = note: `#[warn(unexpected_cfgs)]` on by default
    

    Explanation

    This lint is only active when --check-cfg arguments are being passed to the compiler and triggers whenever an unexpected condition name or value is used.

    See the Checking Conditional Configurations section for more details.

    See the Cargo Specifics section for configuring this lint in Cargo.toml.

    unfulfilled-lint-expectations

    The unfulfilled_lint_expectations lint detects when a lint expectation is unfulfilled.

    Example

    #[expect(unused_variables)]
    let x = 10;
    println!("{}", x);
    

    Explanation

    The #[expect] attribute can be used to create a lint expectation. The expectation is fulfilled, if a #[warn] attribute at the same location would result in a lint emission. If the expectation is unfulfilled, because no lint was emitted, this lint will be emitted on the attribute.

    ungated-async-fn-track-caller

    The ungated_async_fn_track_caller lint warns when the #[track_caller] attribute is used on an async function without enabling the corresponding unstable feature flag.

    Example

    #[track_caller]
    async fn foo() {}
    

    Explanation

    The attribute must be used in conjunction with the async_fn_track_caller feature flag. Otherwise, the #[track_caller] annotation will function as a no-op.

    unknown-diagnostic-attributes

    The unknown_diagnostic_attributes lint detects unknown diagnostic attributes.

    Example

    #[diagnostic::does_not_exist]
    struct Thing;
    

    Explanation

    It is usually a mistake to specify a diagnostic attribute that does not exist. Check the spelling, and check the diagnostic attribute listing for the correct name. Also consider if you are using an old version of the compiler and the attribute is only available in a newer version. See the reference for the list of diagnostic attributes.

    unknown-lints

    The unknown_lints lint detects unrecognized lint attributes.

    Example

    #![allow(not_a_real_lint)]
    

    Explanation

    It is usually a mistake to specify a lint that does not exist. Check the spelling, and check the lint listing for the correct name. Also consider if you are using an old version of the compiler, and the lint is only available in a newer version.

    unnameable-test-items

    The unnameable_test_items lint detects #[test] functions that are not able to be run by the test harness because they are in a position where they are not nameable.

    Example

    fn main() {
        #[test]
        fn foo() {
            // This test will not fail because it does not run.
            assert_eq!(1, 2);
        }
    }
    

    Explanation

    In order for the test harness to run a test, the test function must be located in a position where it can be accessed from the crate root. This generally means it must be defined in a module, and not anywhere else such as inside another function. The compiler previously allowed this without an error, so a lint was added as an alert that a test is not being used. Whether or not this should be allowed has not yet been decided, see RFC 2471 and issue #36629.

    unnecessary-transmutes

    The unnecessary_transmutes lint detects transmutations that have safer alternatives.

    Example

    fn bytes_at_home(x: [u8; 4]) -> u32 {
      unsafe { std::mem::transmute(x) }
    }
    

    Explanation

    Using an explicit method is preferable over calls to transmute as they more clearly communicate the intent, are easier to review, and are less likely to accidentally result in unsoundness.

    unpredictable-function-pointer-comparisons

    The unpredictable_function_pointer_comparisons lint checks comparison of function pointer as the operands.

    Example

    fn a() {}
    fn b() {}
    
    let f: fn() = a;
    let g: fn() = b;
    
    let _ = f == g;
    

    Explanation

    Function pointers comparisons do not produce meaningful result since they are never guaranteed to be unique and could vary between different code generation units. Furthermore, different functions could have the same address after being merged together.

    unreachable-cfg-select-predicates

    The unreachable_cfg_select_predicates lint detects unreachable configuration predicates in the cfg_select! macro.

    Example

    cfg_select! {
        _ => (),
        windows => (),
    }
    

    Explanation

    This usually indicates a mistake in how the predicates are specified or ordered. In this example, the _ predicate will always match, so the windows is impossible to reach. Remember, arms match in order, you probably wanted to put the windows case above the _ case.

    unreachable-code

    The unreachable_code lint detects unreachable code paths.

    Example

    panic!("we never go past here!");
    
    let x = 5;
    

    Explanation

    Unreachable code may signal a mistake or unfinished code. If the code is no longer in use, consider removing it.

    unreachable-patterns

    The unreachable_patterns lint detects unreachable patterns.

    Example

    let x = 5;
    match x {
        y => (),
        5 => (),
    }
    

    Explanation

    This usually indicates a mistake in how the patterns are specified or ordered. In this example, the y pattern will always match, so the five is impossible to reach. Remember, match arms match in order, you probably wanted to put the 5 case above the y case.

    unsafe-panic-handlers

    The unsafe_panic_handlers lint detects unsafe functions with the #[panic_handler] attribute.

    Example

    #![no_std]
    
    use core::panic::PanicInfo;
    
    #[panic_handler]
    unsafe fn handle(_: &PanicInfo<'_>) -> ! {
        loop {}
    }
    

    Explanation

    Unsafe functions (declared as unsafe fn) are functions that can only be called when the caller ensures that their safety requirements are met. On the other hand, #[panic_handler] functions get called automatically by the compiler without checking for any preconditions. Therefore, using the #[panic_handler] attribute on unsafe functions is either incorrect or a misuse of unsafe fn.

    This is a future-incompatible lint to transition this to a hard error in the future. See issue #163263 for more details.

    unstable-name-collision

    The lint unstable-name-collision has been renamed to unstable-name-collisions.

    unstable-name-collisions

    The unstable_name_collisions lint detects that you have used a name that the standard library plans to add in the future.

    Example

    trait MyIterator : Iterator {
        // is_partitioned is an unstable method that already exists on the Iterator trait
        fn is_partitioned<P>(self, predicate: P) -> bool
        where
            Self: Sized,
            P: FnMut(Self::Item) -> bool,
        {true}
    }
    
    impl<T: ?Sized> MyIterator for T where T: Iterator { }
    
    let x = vec![1, 2, 3];
    let _ = x.iter().is_partitioned(|_| true);
    

    Explanation

    When new methods are added to traits in the standard library, they are usually added in an “unstable” form which is only available on the nightly channel with a feature attribute. If there is any preexisting code which extends a trait to have a method with the same name, then the names will collide. In the future, when the method is stabilized, this will cause an error due to the ambiguity. This lint is an early-warning to let you know that there may be a collision in the future. This can be avoided by adding type annotations to disambiguate which trait method you intend to call, such as MyIterator::is_partitioned(my_iter, my_predicate) or renaming or removing the method.

    unstable-syntax-pre-expansion

    The unstable_syntax_pre_expansion lint detects the use of unstable syntax that is discarded during attribute expansion.

    Example

    #[cfg(feature = "nightly")]
    macro foo() {}
    

    Explanation

    The input to active attributes such as #[cfg] or procedural macro attributes is required to be valid syntax. Previously, the compiler only gated the use of unstable syntax features after resolving #[cfg] gates and expanding procedural macros.

    To avoid relying on unstable syntax, move the use of unstable syntax into a position where the compiler does not parse the syntax, such as a functionlike macro.

    
    macro_rules! identity {
       ( $($tokens:tt)* ) => { $($tokens)* }
    }
    
    #[cfg(feature = "nightly")]
    identity! {
       macro foo() {}
    }
    

    This is a future-incompatible lint to transition this to a hard error in the future. See issue #154045 for more details.

    unsupported-calling-conventions

    The unsupported_calling_conventions lint is output whenever there is a use of the stdcall, fastcall, and cdecl calling conventions (or their unwind variants) on targets that cannot meaningfully be supported for the requested target.

    For example, stdcall does not make much sense for a x86_64 or, more apparently, powerpc code, because this calling convention was never specified for those targets.

    Historically, MSVC toolchains have fallen back to the regular C calling convention for targets other than x86, but Rust doesn’t really see a similar need to introduce a similar hack across many more targets.

    Example

    extern "stdcall" fn stdcall() {}
    

    This will produce:

    warning: use of calling convention not supported on this target
      --> $DIR/unsupported.rs:39:1
       |
    LL | extern "stdcall" fn stdcall() {}
       | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
       |
       = note: `#[warn(unsupported_calling_conventions)]` on by default
       = warning: this was previously accepted by the compiler but is being phased out;
                  it will become a hard error in a future release!
       = note: for more information, see issue ...
    

    Explanation

    On most of the targets, the behaviour of stdcall and similar calling conventions is not defined at all, but was previously accepted due to a bug in the implementation of the compiler.

    unsupported-fn-ptr-calling-conventions

    The unsupported_fn_ptr_calling_conventions lint is output whenever there is a use of a target dependent calling convention on a target that does not support this calling convention on a function pointer.

    For example stdcall does not make much sense for a x86_64 or, more apparently, powerpc code, because this calling convention was never specified for those targets.

    Example

    fn stdcall_ptr(f: extern "stdcall" fn ()) {
        f()
    }
    

    This will produce:

    warning: the calling convention `"stdcall"` is not supported on this target
      --> $DIR/unsupported.rs:34:15
       |
    LL | fn stdcall_ptr(f: extern "stdcall" fn()) {
       |               ^^^^^^^^^^^^^^^^^^^^^^^^
       |
       = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
       = note: for more information, see issue #130260 <https://github.com/rust-lang/rust/issues/130260>
       = note: `#[warn(unsupported_fn_ptr_calling_conventions)]` on by default
    

    Explanation

    On most of the targets the behaviour of stdcall and similar calling conventions is not defined at all, but was previously accepted due to a bug in the implementation of the compiler.

    unused-allocation

    The unused_allocation lint detects unnecessary allocations that can be eliminated.

    Example

    fn main() {
        let a = Box::new([1, 2, 3]).len();
    }
    

    Explanation

    When a box expression is immediately coerced to a reference, then the allocation is unnecessary, and a reference (using & or &mut) should be used instead to avoid the allocation.

    unused-assignments

    The unused_assignments lint detects assignments that will never be read.

    Example

    let mut x = 5;
    x = 6;
    

    Explanation

    Unused assignments may signal a mistake or unfinished code. If the variable is never used after being assigned, then the assignment can be removed. Variables with an underscore prefix such as _x will not trigger this lint.

    unused-associated-type-bounds

    The unused_associated_type_bounds lint is emitted when an associated type bound is added to a trait object, but the associated type has a where Self: Sized bound, and is thus unavailable on the trait object anyway.

    Example

    trait Foo {
        type Bar where Self: Sized;
    }
    type Mop = dyn Foo<Bar = ()>;
    

    Explanation

    Just like methods with Self: Sized bounds are unavailable on trait objects, associated types can be removed from the trait object.

    unused-attributes

    The unused_attributes lint detects attributes that were not used by the compiler.

    Example

    #![ignore]
    

    Explanation

    Unused attributes may indicate the attribute is placed in the wrong position. Consider removing it, or placing it in the correct position. Also consider if you intended to use an inner attribute (with a ! such as #![allow(unused)]) which applies to the item the attribute is within, or an outer attribute (without a ! such as #[allow(unused)]) which applies to the item following the attribute.

    unused-braces

    The unused_braces lint detects unnecessary braces around an expression.

    Example

    if { true } {
        // ...
    }
    

    Explanation

    The braces are not needed, and should be removed. This is the preferred style for writing these expressions.

    unused-comparisons

    The unused_comparisons lint detects comparisons made useless by limits of the types involved.

    Example

    fn foo(x: u8) {
        x >= 0;
    }
    

    Explanation

    A useless comparison may indicate a mistake, and should be fixed or removed.

    unused-doc-comment

    The lint unused-doc-comment has been renamed to unused-doc-comments.

    unused-doc-comments

    The unused_doc_comments lint detects doc comments that aren’t used by rustdoc.

    Example

    /// docs for x
    let x = 12;
    

    Explanation

    rustdoc does not use doc comments in all positions, and so the doc comment will be ignored. Try changing it to a normal comment with // to avoid the warning.

    unused-features

    The unused_features lint detects unused or unknown features found in crate-level feature attributes.

    unused-imports

    The unused_imports lint detects imports that are never used.

    Example

    use std::collections::HashMap;
    

    Explanation

    Unused imports may signal a mistake or unfinished code, and clutter the code, and should be removed. If you intended to re-export the item to make it available outside of the module, add a visibility modifier like pub.

    unused-labels

    The unused_labels lint detects labels that are never used.

    Example

    'unused_label: loop {}
    

    Explanation

    Unused labels may signal a mistake or unfinished code. To silence the warning for the individual label, prefix it with an underscore such as '_my_label:.

    unused-macros

    The unused_macros lint detects macros that were not used.

    Note that this lint is distinct from the unused_macro_rules lint, which checks for single rules that never match of an otherwise used macro, and thus never expand.

    Example

    macro_rules! unused {
        () => {};
    }
    
    fn main() {
    }
    

    Explanation

    Unused macros may signal a mistake or unfinished code. To silence the warning for the individual macro, prefix the name with an underscore such as _my_macro. If you intended to export the macro to make it available outside of the crate, use the macro_export attribute.

    unused-must-use

    The unused_must_use lint detects unused result of a type flagged as #[must_use].

    Example

    fn returns_result() -> Result<(), ()> {
        Ok(())
    }
    
    fn main() {
        returns_result();
    }
    

    Explanation

    The #[must_use] attribute is an indicator that it is a mistake to ignore the value. See the reference for more details.

    unused-mut

    The unused_mut lint detects mut variables which don’t need to be mutable.

    Example

    let mut x = 5;
    

    Explanation

    The preferred style is to only mark variables as mut if it is required.

    unused-parens

    The unused_parens lint detects if, match, while and return with parentheses; they do not need them.

    Examples

    if(true) {}
    

    Explanation

    The parentheses are not needed, and should be removed. This is the preferred style for writing these expressions.

    unused-tuple-struct-fields

    The lint unused-tuple-struct-fields has been renamed to dead-code.

    unused-unsafe

    The unused_unsafe lint detects unnecessary use of an unsafe block.

    Example

    unsafe {}
    

    Explanation

    If nothing within the block requires unsafe, then remove the unsafe marker because it is not required and may cause confusion.

    unused-variables

    The unused_variables lint detects variables which are not used in any way.

    Example

    let x = 5;
    

    Explanation

    Unused variables may signal a mistake or unfinished code. To silence the warning for the individual variable, prefix it with an underscore such as _x.

    unused-visibilities

    The unused_visibilities lint detects visibility qualifiers (like pub) on a const _ item.

    Example

    pub const _: () = {};
    

    Explanation

    These qualifiers have no effect, as const _ items are unnameable.

    useless-ptr-null-checks

    The useless_ptr_null_checks lint checks for useless null checks against pointers obtained from non-null types.

    Example

    let fn_ptr: fn() = /* somehow obtained nullable function pointer */
    
    if (fn_ptr as *const ()).is_null() { /* ... */ }
    

    Explanation

    Function pointers and references are assumed to be non-null, checking them for null will always return false.

    uses-power-alignment

    The uses_power_alignment lint detects specific repr(C) aggregates on AIX. In its platform C ABI, AIX uses the “power” (as in PowerPC) alignment rule (detailed in https://www.ibm.com/docs/en/xl-c-and-cpp-aix/16.1?topic=data-using-alignment-modes#alignment), which can also be set for XLC by #pragma align(power) or -qalign=power. Aggregates with a floating-point type as the recursively first field (as in “at offset 0”) modify the layout of subsequent fields of the associated structs to use an alignment value where the floating-point type is aligned on a 4-byte boundary.

    Effectively, subsequent floating-point fields act as-if they are repr(packed(4)). This would be unsound to do in a repr(C) type without all the restrictions that come with repr(packed). Rust instead chooses a layout that maintains soundness of Rust code, at the expense of incompatibility with C code.

    Example

    #[repr(C)]
    pub struct Floats {
        a: f64,
        b: u8,
        c: f64,
    }
    

    This will produce:

    warning: repr(C) does not follow the power alignment rule. This may affect platform C ABI compatibility for this type
     --> <source>:5:3
      |
    5 |   c: f64,
      |   ^^^^^^
      |
      = note: `#[warn(uses_power_alignment)]` on by default
    

    Explanation

    The power alignment rule specifies that the above struct has the following alignment:

    • offset_of!(Floats, a) == 0
    • offset_of!(Floats, b) == 8
    • offset_of!(Floats, c) == 12

    However, Rust currently aligns c at offset_of!(Floats, c) == 16. Using offset 12 would be unsound since f64 generally must be 8-aligned on this target. Thus, a warning is produced for the above struct.

    warnings

    The warnings lint allows you to change the level of other lints which produce warnings.

    Example

    #![deny(warnings)]
    struct non_standard_name;
    

    Explanation

    The warnings lint is a bit special; by changing its level, you change every other warning that would produce a warning to whatever value you’d like. As such, you won’t ever trigger this lint in your code directly.

    while-true

    The while_true lint detects while true { }.

    Example

    while true {
    
    }
    

    Explanation

    while true should be replaced with loop. A loop expression is the preferred way to write an infinite loop because it more directly expresses the intent of the loop.

  3. I.e., paths of the form T::Assoc where T is a type parameter bounded by trait Trait which defines an associated type called Assoc as opposed to a fully qualified path of the form <T as Trait>::Assoc. ↩

  4. https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes ↩