Allowed-by-default Lints
These lints are all set to the ‘allow’ level by default. As such, they won’t show up unless you set them to a higher lint level with a flag or attribute.
absolute_paths_not_starting_with_crateambiguous_negative_literalsasync_identsclosure_returning_async_blockdead_code_pub_in_binarydeprecated_llvm_intrinsicdeprecated_safe_2024deref_into_dyn_supertraitdisjoint_capture_migrationedition_2024_expr_fragment_specifierelided_lifetime_in_pathelided_lifetimes_in_pathsexplicit_outlives_requirementsffi_unwind_callsif_let_rescopeimpl_trait_overcapturesimpl_trait_redundant_capturesimplicit_provenance_castskeyword_identskeyword_idents_2018keyword_idents_2024let_underscore_droplinker_infomacro_use_extern_cratemeta_variable_misusemissing_copy_implementationsmissing_debug_implementationsmissing_docsmissing_unsafe_on_externmultiple_supertrait_upcastablemust_not_suspendnon_ascii_identsnon_exhaustive_omitted_patternsor_patterns_back_compatraw_borrows_via_referencesredundant_importsredundant_lifetimesresolving_to_items_shadowing_supertrait_itemsrust_2021_incompatible_closure_capturesrust_2021_incompatible_or_patternsrust_2021_prefixes_incompatible_syntaxrust_2021_prelude_collisionsrust_2024_guarded_string_incompatible_syntaxrust_2024_incompatible_patrust_2024_prelude_collisionsshadowing_supertrait_itemssingle_use_lifetimesingle_use_lifetimestail_expr_drop_ordertrivial_caststrivial_numeric_castsunit_bindingsunnameable_typesunqualified_local_importsunreachable_pubunsafe_attr_outside_unsafeunsafe_codeunsafe_op_in_unsafe_fnunstable_featuresunused_crate_dependenciesunused_extern_cratesunused_import_bracesunused_lifetimesunused_macro_rulesunused_qualificationsunused_resultsvariant_size_differences
absolute-paths-not-starting-with-crate
The absolute_paths_not_starting_with_crate lint detects fully
qualified paths that start with a module name instead of crate,
self, or an extern crate name
Example
Explanation
Rust editions allow the language to evolve without breaking
backwards compatibility. This lint catches code that uses absolute
paths in the style of the 2015 edition. In the 2015 edition, absolute
paths (those starting with ::) refer to either the crate root or an
external crate. In the 2018 edition it was changed so that they only
refer to external crates. The path prefix crate:: should be used
instead to reference items from the crate root.
If you switch the compiler from the 2015 to 2018 edition without
updating the code, then it will fail to compile if the old style paths
are used. You can manually change the paths to use the crate::
prefix to transition to the 2018 edition.
This lint solves the problem automatically. It is “allow” by default
because the code is perfectly valid in the 2015 edition. The cargo fix tool with the --edition flag will switch this lint to “warn”
and automatically apply the suggested fix from the compiler. This
provides a completely automated way to update old code to the 2018
edition.
ambiguous-negative-literals
The ambiguous_negative_literals lint checks for cases that are
confusing between a negative literal and a negation that’s not part
of the literal.
Example
-1i32.abs; // equals -1, while `(-1i32).abs()` equals 1
Explanation
Method calls take precedence over unary precedence. Setting the precedence explicitly makes the code clearer and avoid potential bugs.
async-idents
The lint async-idents has been renamed to keyword-idents.
closure-returning-async-block
The closure_returning_async_block lint detects cases where users
write a closure that returns an async block.
Example
let c = ;
Explanation
Using an async closure is preferable over a closure that returns an async block, since async closures are less restrictive in how its captures are allowed to be used.
For example, this code does not work with a closure returning an async block:
async
let captured_str = Stringnew;
let c = move || async ;
But it does work with async closures:
async
let captured_str = Stringnew;
let c = async move || ;
dead-code-pub-in-binary
The dead_code_pub_in_binary lint detects unused pub items in
executable crates.
Example
Explanation
In executable crates, pub items are often implementation details
rather than part of an external API. This lint helps find those items
when they are never used.
This lint only applies to executable crates. In library crates, public items are considered part of the crate’s API and are not reported by this lint.
deprecated-llvm-intrinsic
The deprecated_llvm_intrinsic lint detects usage of deprecated LLVM intrinsics.
Example
unsafe extern "llvm-intrinsic"
This will produce:
error: Using deprecated intrinsic `llvm.x86.addcarryx.u32`
--> example.rs:7:5
|
7 | fn foo(a: u8, b: u32, c: u32, d: &mut u32) -> u8;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
Explanation
LLVM periodically updates its list of intrinsics. Deprecated intrinsics are unlikely to be removed, but they may optimize less well than their new versions, so it’s best to use the new version. Also, some deprecated intrinsics might have buggy behavior.
This link_llvm_intrinsics lint is intended to be used internally only, and requires the
#![feature(link_llvm_intrinsics)] internal feature gate. For more information, see its chapter in
the Unstable Book
and its tracking issue.
deprecated-safe-2024
The deprecated_safe_2024 lint detects unsafe functions being used as
safe functions.
Example
// edition 2021
use env;
Explanation
Rust editions allow the language to evolve without breaking backward
compatibility. This lint catches code that uses unsafe functions that
were declared as safe (non-unsafe) in editions prior to Rust 2024. If
you switch the compiler to Rust 2024 without updating the code, then it
will fail to compile if you are using a function previously marked as
safe.
You can audit the code to see if it suffices the preconditions of the
unsafe code, and if it does, you can wrap it in an unsafe block. If
you can’t fulfill the preconditions, you probably need to switch to a
different way of doing what you want to achieve.
This lint can automatically wrap the calls in unsafe blocks, but this
obviously cannot verify that the preconditions of the unsafe
functions are fulfilled, so that is still up to the user.
The lint is currently “allow” by default, but that might change in the future.
deref-into-dyn-supertrait
The deref_into_dyn_supertrait lint is emitted whenever there is a Deref implementation
for dyn SubTrait with a dyn SuperTrait type as the Output type.
These implementations are “shadowed” by trait upcasting (stabilized since
1.86.0). The deref functions is no longer called implicitly, which might
change behavior compared to previous rustc versions.
Example
use Deref;
Explanation
The trait upcasting coercion added a new coercion rule, taking priority over certain other
coercion rules, which causes some behavior change compared to older rustc versions.
deref can be still called explicitly, it just isn’t called as part of a deref coercion
(since trait upcasting coercion takes priority).
disjoint-capture-migration
The lint disjoint-capture-migration has been renamed to rust-2021-incompatible-closure-captures.
edition-2024-expr-fragment-specifier
The edition_2024_expr_fragment_specifier lint detects the use of
expr fragments in macros during migration to the 2024 edition.
The expr fragment specifier will accept more expressions in the 2024
edition. To maintain the behavior from the 2021 edition and earlier, use
the expr_2021 fragment specifier.
Example
Explanation
Rust editions allow the language to evolve without breaking backwards compatibility. This lint catches code that uses macro matcher fragment specifiers that have changed meaning in the 2024 edition. If you switch to the new edition without updating the code, your macros may behave differently.
In the 2024 edition, the expr fragment specifier expr will also
match const { ... } blocks. This means if a macro had a pattern that
matched $e:expr and another that matches const { $e: expr }, for
example, that under the 2024 edition the first pattern would match while
in the 2021 and earlier editions the second pattern would match. To keep
the old behavior, use the expr_2021 fragment specifier.
This lint detects macros whose behavior might change due to the changing
meaning of the expr fragment specifier. It is “allow” by default
because the code is perfectly valid in older editions. The cargo fix
tool with the --edition flag will switch this lint to “warn” and
automatically apply the suggested fix from the compiler. This provides a
completely automated way to update old code for a new edition.
Using cargo fix --edition with this lint will ensure that your code
retains the same behavior. This may not be the desired, as macro authors
often will want their macros to use the latest grammar for matching
expressions. Be sure to carefully review changes introduced by this lint
to ensure the macros implement the desired behavior.
elided-lifetime-in-path
The lint elided-lifetime-in-path has been renamed to elided-lifetimes-in-paths.
elided-lifetimes-in-paths
The elided_lifetimes_in_paths lint detects the use of hidden
lifetime parameters.
Example
Explanation
Elided lifetime parameters can make it difficult to see at a glance
that borrowing is occurring. This lint ensures that lifetime
parameters are always explicitly stated, even if it is the '_
placeholder lifetime.
This lint is “allow” by default because it has some known issues, and may require a significant transition for old code.
explicit-outlives-requirements
The explicit_outlives_requirements lint detects unnecessary
lifetime bounds that can be inferred.
Example
Explanation
If a struct, enum or union contains a reference, such as &'a T,
the compiler requires that T outlives the lifetime 'a.
This historically required writing an explicit lifetime bound to indicate this requirement.
However, this can be overly explicit, causing clutter and unnecessary complexity.
The language was changed to automatically infer some classes of lifetime bounds
if they are not specified.
Specifically, if a struct, enum or union contains a reference, directly or indirectly,
to T with lifetime 'x and 'x refers to a lifetime parameter,
then it will infer that T: 'x is a requirement.
See RFC 2093 for more details.
Note
This lint intentionally doesn’t get emitted for explicit outlives-bounds on type
parameters that aren’t bounded by Sized (unless they’re higher-ranked) since unlike
implicit outlives-bounds these may affect the implicit lifetime bound of trait object
types that are passed as arguments to the overarching struct, enum or union.
Rephrased, they participate in trait object lifetime defaulting.
Consider the following piece of code where removing bound T: 'a would lead to a lifetime
error in function scope:
;
Due to the explicit outlives-bound the function render above is equivalent to:
If it wasn’t for that explicit bound then the function would mean the following instead:
ffi-unwind-calls
The ffi_unwind_calls lint detects calls to foreign functions or function pointers with
C-unwind or other FFI-unwind ABIs.
Example
unsafe extern "C-unwind"
Explanation
For crates containing such calls, if they are compiled with -C panic=unwind then the
produced library cannot be linked with crates compiled with -C panic=abort. For crates
that desire this ability it is therefore necessary to avoid such calls.
if-let-rescope
The if_let_rescope lint detects cases where a temporary value with
significant drop is generated on the right hand side of if let
and suggests a rewrite into match when possible.
Example
;
Explanation
With Edition 2024, temporaries generated while evaluating if lets
will be dropped before the else block.
This lint captures a possible change in runtime behaviour due to
a change in sequence of calls to significant Drop::drop destructors.
A significant Drop::drop
destructor here refers to an explicit, arbitrary implementation of the Drop trait on the type
with exceptions including Vec, Box, Rc, BTreeMap and HashMap
that are marked by the compiler otherwise so long that the generic types have
no significant destructor recursively.
In other words, a type has a significant drop destructor when it has a Drop implementation
or its destructor invokes a significant destructor on a type.
Since we cannot completely reason about the change by just inspecting the existence of
a significant destructor, this lint remains only a suggestion and is set to allow by default.
Whenever possible, a rewrite into an equivalent match expression that
observe the same order of calls to such destructors is proposed by this lint.
Authors may take their own discretion whether the rewrite suggestion shall be
accepted, or rejected to continue the use of the if let expression.
impl-trait-overcaptures
The impl_trait_overcaptures lint warns against cases where lifetime
capture behavior will differ in edition 2024.
In the 2024 edition, impl Traits will capture all lifetimes in scope,
rather than just the lifetimes that are mentioned in the bounds of the type.
Often these sets are equal, but if not, it means that the impl Trait may
cause erroneous borrow-checker errors.
Example
let mut x = vec!;
x.push;
let element = test;
x.push;
println!;
Explanation
In edition < 2024, the returned impl Display doesn’t capture the
lifetime from the &Vec<i32>, so the vector can be mutably borrowed
while the impl Display is live.
To fix this, we can explicitly state that the impl Display doesn’t
capture any lifetimes, using impl Display + use<>.
impl-trait-redundant-captures
The impl_trait_redundant_captures lint warns against cases where use of the
precise capturing use<...> syntax is not needed.
In the 2024 edition, impl Traits will capture all lifetimes in scope.
If precise-capturing use<...> syntax is used, and the set of parameters
that are captures are equal to the set of parameters in scope, then
the syntax is redundant, and can be removed.
Example
+ use<'a>
Explanation
To fix this, remove the use<'a>, since the lifetime is already captured
since it is in scope.
implicit-provenance-casts
The implicit_provenance_casts lint detects integer-to-pointer and pointer-to-integer
casts.
Example
Explanation
This lint exists to help migrate code to Strict Provenance APIs where
possible, and make remaining uses of Exposed Provenance explicit.
For more information on pointer provenance, see the std::ptr documentation.
Earlier versions of Rust did not have a clear answer how integer-to-pointer and pointer-to-integer casts interact with provenance. Such casts are now defined to use the exposed provenance model, but in many cases the code can be updated to strict provenance APIs, which is preferable as it enables more precise reasoning about unsafe code, both by humans and by tools like Miri.
However, there are situations where exposed provenance is required or following the strict
provenance model requires major refactorings. In those cases, it’s still useful to replace
the as casts with equivalent explicit use of exposed provenance APIs and a comment
explaining why they are needed.
keyword-idents
The lint keyword-idents has been renamed to keyword-idents-2018.
keyword-idents-2018
The keyword_idents_2018 lint detects edition keywords being used as an
identifier.
Example
// edition 2015
Explanation
Rust editions allow the language to evolve without breaking backwards compatibility. This lint catches code that uses new keywords that are added to the language that are used as identifiers (such as a variable name, function name, etc.). If you switch the compiler to a new edition without updating the code, then it will fail to compile if you are using a new keyword as an identifier.
You can manually change the identifiers to a non-keyword, or use a
raw identifier, for example r#dyn, to transition to a new edition.
This lint solves the problem automatically. It is “allow” by default
because the code is perfectly valid in older editions. The cargo fix tool with the --edition flag will switch this lint to “warn”
and automatically apply the suggested fix from the compiler (which is
to use a raw identifier). This provides a completely automated way to
update old code for a new edition.
keyword-idents-2024
The keyword_idents_2024 lint detects edition keywords being used as an
identifier.
Example
// edition 2015
Explanation
Rust editions allow the language to evolve without breaking backwards compatibility. This lint catches code that uses new keywords that are added to the language that are used as identifiers (such as a variable name, function name, etc.). If you switch the compiler to a new edition without updating the code, then it will fail to compile if you are using a new keyword as an identifier.
You can manually change the identifiers to a non-keyword, or use a
raw identifier, for example r#gen, to transition to a new edition.
This lint solves the problem automatically. It is “allow” by default
because the code is perfectly valid in older editions. The cargo fix tool with the --edition flag will switch this lint to “warn”
and automatically apply the suggested fix from the compiler (which is
to use a raw identifier). This provides a completely automated way to
update old code for a new edition.
let-underscore-drop
The let_underscore_drop lint checks for statements which don’t bind
an expression which has a non-trivial Drop implementation to anything,
causing the expression to be dropped immediately instead of at end of
scope.
Example
;
Explanation
Statements which assign an expression to an underscore causes the
expression to immediately drop instead of extending the expression’s
lifetime to the end of the scope. This is usually unintended,
especially for types like MutexGuard, which are typically used to
lock a mutex for the duration of an entire scope.
If you want to extend the expression’s lifetime to the end of the scope,
assign an underscore-prefixed name (such as _foo) to the expression.
If you do actually want to drop the expression immediately, then
calling std::mem::drop on the expression is clearer and helps convey
intent.
linker-info
The linker_info lint forwards warnings from the linker that are known to be informational-only.
Example
On MacOS, using -C link-arg=-lc and the default linker, this will produce
warning: linker stderr: ld: ignoring duplicate libraries: '-lc'
|
note: the lint level is defined here
--> ex.rs:1:9
|
1 | #![warn(linker_info)]
| ^^^^^^^^^^^^^^^
Explanation
Many linkers are very “chatty” and print lots of information that is not necessarily indicative of an issue. This output has been ignored for many years and is often not actionable by developers. It is silenced unless the developer specifically requests for it to be printed. See this tracking issue for more details: https://github.com/rust-lang/rust/issues/136096.
macro-use-extern-crate
The macro_use_extern_crate lint detects the use of the macro_use attribute.
Example
extern crate serde_json;
This will produce:
error: applying the `#[macro_use]` attribute to an `extern crate` item is deprecated
--> src/main.rs:3:1
|
3 | #[macro_use]
| ^^^^^^^^^^^^
|
= help: remove it and import macros at use sites with a `use` item instead
note: the lint level is defined here
--> src/main.rs:1:9
|
1 | #![deny(macro_use_extern_crate)]
| ^^^^^^^^^^^^^^^^^^^^^^
Explanation
The macro_use attribute on an extern crate item causes
macros in that external crate to be brought into the prelude of the
crate, making the macros in scope everywhere. As part of the efforts
to simplify handling of dependencies in the 2018 edition, the use of
extern crate is being phased out. To bring macros from extern crates
into scope, it is recommended to use a use import.
This lint is “allow” by default because this is a stylistic choice that has not been settled, see issue #52043 for more information.
meta-variable-misuse
The meta_variable_misuse lint detects possible meta-variable misuse
in macro definitions.
Example
Explanation
There are quite a few different ways a macro_rules macro can be
improperly defined. Many of these errors were previously only detected
when the macro was expanded or not at all. This lint is an attempt to
catch some of these problems when the macro is defined.
This lint is “allow” by default because it may have false positives and other issues. See issue #61053 for more details.
missing-copy-implementations
The missing_copy_implementations lint detects potentially-forgotten
implementations of Copy for public types.
Example
Explanation
Historically (before 1.0), types were automatically marked as Copy
if possible. This was changed so that it required an explicit opt-in
by implementing the Copy trait. As part of this change, a lint was
added to alert if a copyable type was not marked Copy.
This lint is “allow” by default because this code isn’t bad; it is
common to write newtypes like this specifically so that a Copy type
is no longer Copy. Copy types can result in unintended copies of
large data which can impact performance.
missing-debug-implementations
The missing_debug_implementations lint detects missing
implementations of fmt::Debug for public types.
Example
;
Explanation
Having a Debug implementation on all types can assist with
debugging, as it provides a convenient way to format and display a
value. Using the #[derive(Debug)] attribute will automatically
generate a typical implementation, or a custom implementation can be
added by manually implementing the Debug trait.
This lint is “allow” by default because adding Debug to all types can
have a negative impact on compile time and code size. It also requires
boilerplate to be added to every type, which can be an impediment.
missing-docs
The missing_docs lint detects missing documentation for public items.
Example
Explanation
This lint is intended to ensure that a library is well-documented. Items without documentation can be difficult for users to understand how to use properly.
This lint is “allow” by default because it can be noisy, and not all projects may want to enforce everything to be documented.
missing-unsafe-on-extern
The missing_unsafe_on_extern lint detects missing unsafe keyword on extern declarations.
Example
extern "C"
Explanation
Declaring extern items, even without ever using them, can cause Undefined Behavior. We should consider all sources of Undefined Behavior to be unsafe.
This is a future-incompatible lint to transition this to a hard error in the future.
multiple-supertrait-upcastable
The multiple_supertrait_upcastable lint detects when a dyn-compatible trait has multiple
supertraits.
Example
Explanation
To support upcasting with multiple supertraits, we need to store multiple vtables and this can result in extra space overhead, even if no code actually uses upcasting. This lint allows users to identify when such scenarios occur and to decide whether the additional overhead is justified.
must-not-suspend
The must_not_suspend lint guards against values that shouldn’t be held across suspend points
(.await)
Example
async
pub async
Explanation
The must_not_suspend lint detects values that are marked with the #[must_not_suspend]
attribute being held across suspend points. A “suspend” point is usually a .await in an async
function.
This attribute can be used to mark values that are semantically incorrect across suspends
(like certain types of timers), values that have async alternatives, and values that
regularly cause problems with the Send-ness of async fn’s returned futures (like
MutexGuard’s)
non-ascii-idents
The non_ascii_idents lint detects non-ASCII identifiers.
Example
Explanation
This lint allows projects that wish to retain the limit of only using ASCII characters to switch this lint to “forbid” (for example to ease collaboration or for security reasons). See RFC 2457 for more details.
non-exhaustive-omitted-patterns
The non_exhaustive_omitted_patterns lint aims to help consumers of a #[non_exhaustive]
struct or enum who want to match all of its fields/variants explicitly.
The #[non_exhaustive] annotation forces matches to use wildcards, so exhaustiveness
checking cannot be used to ensure that all fields/variants are matched explicitly. To remedy
this, this allow-by-default lint warns the user when a match mentions some but not all of
the fields/variants of a #[non_exhaustive] struct or enum.
Example
// crate A
// in crate B
match A
This will produce:
warning: some variants are not matched explicitly
--> $DIR/reachable-patterns.rs:70:9
|
LL | match Bar::A {
| ^ pattern `Bar::B` not covered
|
note: the lint level is defined here
--> $DIR/reachable-patterns.rs:69:16
|
LL | #[warn(non_exhaustive_omitted_patterns)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
= help: ensure that all variants are matched explicitly by adding the suggested match arms
= note: the matched value is of type `Bar` and the `non_exhaustive_omitted_patterns` attribute was found
Warning: setting this to deny will make upstream non-breaking changes (adding fields or
variants to a #[non_exhaustive] struct or enum) break your crate. This goes against
expected semver behavior.
Explanation
Structs and enums tagged with #[non_exhaustive] force the user to add a (potentially
redundant) wildcard when pattern-matching, to allow for future addition of fields or
variants. The non_exhaustive_omitted_patterns lint detects when such a wildcard happens to
actually catch some fields/variants. In other words, when the match without the wildcard
would not be exhaustive. This lets the user be informed if new fields/variants were added.
or-patterns-back-compat
The lint or-patterns-back-compat has been renamed to rust-2021-incompatible-or-patterns.
raw-borrows-via-references
The raw_borrows_via_references lint checks for references that decay immediately into raw borrows.
Example
*const i32
Explanation
Creating unnecessary references is discouraged because it makes code less explicit and can lead to undefined behavior. Creating a reference induces aliasing assumptions that the compiler relies on, so an otherwise-pointless reference can cause undefined behavior even when the reference is never read through. Avoiding them keeps the code more explicit and easier to reason about.
See the Reference for the full set of validity requirements that references must uphold.
This lint is “allow” by default because it will trigger for a large amount of existing Rust code. Eventually it is desired for this to become warn-by-default.
redundant-imports
The redundant_imports lint detects imports that are redundant due to being
imported already; either through a previous import, or being present in
the prelude.
Example
use None;
Explanation
Redundant imports are unnecessary and can be removed to simplify code.
If you intended to re-export the item to make it available outside of the
module, add a visibility modifier like pub.
redundant-lifetimes
The redundant_lifetimes lint detects lifetime parameters that are
redundant because they are equal to another named lifetime.
Example
// `'a = 'static`, so all usages of `'a` can be replaced with `'static`
// `'a = 'b`, so all usages of `'b` can be replaced with `'a`
Explanation
Unused lifetime parameters may signal a mistake or unfinished code. Consider removing the parameter.
resolving-to-items-shadowing-supertrait-items
The resolving_to_items_shadowing_supertrait_items lint detects when the
usage of an item that is provided by both a subtrait and supertrait
is shadowed, preferring the subtrait.
Example
;
MyType.hello;
Explanation
RFC 3624 specified a heuristic in which a supertrait item would be shadowed by a subtrait item when ambiguity occurs during item selection. In order to mitigate side-effects of this happening silently, this lint detects these cases when users want to deny them or fix the call sites.
rust-2021-incompatible-closure-captures
The rust_2021_incompatible_closure_captures lint detects variables that aren’t completely
captured in Rust 2021, such that the Drop order of their fields may differ between
Rust 2018 and 2021.
It can also detect when a variable implements a trait like Send, but one of its fields does not,
and the field is captured by a closure and used with the assumption that said field implements
the same trait as the root variable.
Example of drop reorder
;
Explanation
In the above example, p.y will be dropped at the end of f instead of
with c in Rust 2021.
Example of auto-trait
use thread;
;
unsafe
Explanation
In the above example, only fptr.0 is captured in Rust 2021.
The field is of type *mut i32, which doesn’t implement Send,
making the code invalid as the field cannot be sent between threads safely.
rust-2021-incompatible-or-patterns
The rust_2021_incompatible_or_patterns lint detects usage of old versions of or-patterns.
Example
Explanation
In Rust 2021, the pat matcher will match additional patterns, which include the | character.
rust-2021-prefixes-incompatible-syntax
The rust_2021_prefixes_incompatible_syntax lint detects identifiers that will be parsed as a
prefix instead in Rust 2021.
Example
m!;
Explanation
In Rust 2015 and 2018, z"hey" is two tokens: the identifier z
followed by the string literal "hey". In Rust 2021, the z is
considered a prefix for "hey".
This lint suggests to add whitespace between the z and "hey" tokens
to keep them separated in Rust 2021.
rust-2021-prelude-collisions
The rust_2021_prelude_collisions lint detects the usage of trait methods which are ambiguous
with traits added to the prelude in future editions.
Example
Explanation
In Rust 2021, one of the important introductions is the prelude changes, which add
TryFrom, TryInto, and FromIterator into the standard library’s prelude. Since this
results in an ambiguity as to which method/function to call when an existing try_into
method is called via dot-call syntax or a try_from/from_iter associated function
is called directly on a type.
rust-2024-guarded-string-incompatible-syntax
The rust_2024_guarded_string_incompatible_syntax lint detects # tokens
that will be parsed as part of a guarded string literal in Rust 2024.
Example
m!;
m!;
Explanation
Prior to Rust 2024, #"hey"# is three tokens: the first #
followed by the string literal "hey" then the final #.
In Rust 2024, the whole sequence is considered a single token.
This lint suggests to add whitespace between the leading #
and the string to keep them separated in Rust 2024.
rust-2024-incompatible-pat
The rust_2024_incompatible_pat lint
detects patterns whose meaning will change in the Rust 2024 edition.
Example
if let Some = &Some
if let Some = &mut Some
Explanation
In Rust 2024 and above, the mut keyword does not reset the pattern binding mode,
and nor do & or &mut patterns. The lint will suggest code that
has the same meaning in all editions.
rust-2024-prelude-collisions
The rust_2024_prelude_collisions lint detects the usage of trait methods which are ambiguous
with traits added to the prelude in future editions.
Example
Explanation
Rust 2024, introduces two new additions to the standard library’s prelude:
Future and IntoFuture. This results in an ambiguity as to which method/function
to call when an existing poll/into_future method is called via dot-call syntax or
a poll/into_future associated function is called directly on a type.
shadowing-supertrait-items
The shadowing_supertrait_items lint detects when the
definition of an item that is provided by both a subtrait and
supertrait is shadowed, preferring the subtrait.
Example
Explanation
RFC 3624 specified a heuristic in which a supertrait item would be shadowed by a subtrait item when ambiguity occurs during item selection. In order to mitigate side-effects of this happening silently, this lint detects these cases when users want to deny them or fix their trait definitions.
single-use-lifetime
The lint single-use-lifetime has been renamed to single-use-lifetimes.
single-use-lifetimes
The single_use_lifetimes lint detects lifetimes that are only used
once.
Example
Explanation
Specifying an explicit lifetime like 'a in a function or impl
should only be used to link together two things. Otherwise, you should
just use '_ to indicate that the lifetime is not linked to anything,
or elide the lifetime altogether if possible.
This lint is “allow” by default because it was introduced at a time
when '_ and elided lifetimes were first being introduced, and this
lint would be too noisy. Also, there are some known false positives
that it produces. See RFC 2115 for historical context, and issue
#44752 for more details.
tail-expr-drop-order
The tail_expr_drop_order lint looks for those values generated at the tail expression location,
that runs a custom Drop destructor.
Some of them may be dropped earlier in Edition 2024 that they used to in Edition 2021 and prior.
This lint detects those cases and provides you information on those values and their custom destructor implementations.
Your discretion on this information is required.
Example
;
Explanation
In tail expression of blocks or function bodies,
values of type with significant Drop implementation has an ill-specified drop order
before Edition 2024 so that they are dropped only after dropping local variables.
Edition 2024 introduces a new rule with drop orders for them,
so that they are dropped first before dropping local variables.
A significant Drop::drop destructor here refers to an explicit, arbitrary
implementation of the Drop trait on the type, with exceptions including Vec,
Box, Rc, BTreeMap and HashMap that are marked by the compiler otherwise
so long that the generic types have no significant destructor recursively.
In other words, a type has a significant drop destructor when it has a Drop implementation
or its destructor invokes a significant destructor on a type.
Since we cannot completely reason about the change by just inspecting the existence of
a significant destructor, this lint remains only a suggestion and is set to allow by default.
This lint only points out the issue with Droppy, which will be dropped before another_droppy
does in Edition 2024.
No fix will be proposed by this lint.
However, the most probable fix is to hoist Droppy into its own local variable binding.
;
trivial-casts
The trivial_casts lint detects trivial casts which could be replaced
with coercion, which may require a temporary variable.
Example
let x: &u32 = &42;
let y = x as *const u32;
Explanation
A trivial cast is a cast e as T where e has type U and U is a
subtype of T. This type of cast is usually unnecessary, as it can be
usually be inferred.
This lint is “allow” by default because there are situations, such as with FFI interfaces or complex type aliases, where it triggers incorrectly, or in situations where it will be more difficult to clearly express the intent. It may be possible that this will become a warning in the future, possibly with an explicit syntax for coercions providing a convenient way to work around the current issues. See RFC 401 (coercions), RFC 803 (type ascription) and RFC 3307 (remove type ascription) for historical context.
trivial-numeric-casts
The trivial_numeric_casts lint detects trivial numeric casts of types
which could be removed.
Example
let x = 42_i32 as i32;
Explanation
A trivial numeric cast is a cast of a numeric type to the same numeric type. This type of cast is usually unnecessary.
This lint is “allow” by default because there are situations, such as with FFI interfaces or complex type aliases, where it triggers incorrectly, or in situations where it will be more difficult to clearly express the intent. It may be possible that this will become a warning in the future, possibly with an explicit syntax for coercions providing a convenient way to work around the current issues. See RFC 401 (coercions), RFC 803 (type ascription) and RFC 3307 (remove type ascription) for historical context.
unit-bindings
The unit_bindings lint detects cases where bindings are useless because they have
the unit type () as their inferred type. The lint is suppressed if the user explicitly
annotates the let binding with the unit type (), or if the let binding uses an underscore
wildcard pattern, i.e. let _ = expr, or if the binding is produced from macro expansions.
Example
Explanation
Creating a local binding with the unit type () does not do much and can be a sign of a
user error, such as in this example:
unnameable-types
The unnameable_types lint detects types for which you can get objects of that type,
but cannot name the type itself.
Example
Explanation
It is often expected that if you can obtain an object of type T, then
you can name the type T as well; this lint attempts to enforce this rule.
The recommended action is to either reexport the type properly to make it nameable,
or document that users are not supposed to be able to name it for one reason or another.
Besides types, this lint applies to traits because traits can also leak through signatures,
and you may obtain objects of their dyn Trait or impl Trait types.
unqualified-local-imports
The unqualified_local_imports lint checks for use items that import a local item using a
path that does not start with self::, super::, or crate::.
Example
use S;
Explanation
This lint is meant to be used with the (unstable) rustfmt setting group_imports = "StdExternalCrate".
That setting makes rustfmt group self::, super::, and crate:: imports separately from those
referring to other crates. However, rustfmt cannot know whether use c::S; refers to a local module c
or an external crate c, so it always gets categorized as an import from another crate.
To ensure consistent grouping of imports from the local crate, all local imports must
start with self::, super::, or crate::. This lint can be used to enforce that style.
unreachable-pub
The unreachable_pub lint triggers for pub items not reachable from other crates - that
means neither directly accessible, nor reexported (with pub use), nor leaked through
things like return types (which the unnameable_types lint can detect if desired).
Example
Explanation
The pub keyword both expresses an intent for an item to be publicly available, and also
signals to the compiler to make the item publicly accessible. The intent can only be
satisfied, however, if all items which contain this item are also publicly accessible.
Thus, this lint serves to identify situations where the intent does not match the reality.
If you wish the item to be accessible elsewhere within the crate, but not outside it, the
pub(crate) visibility is recommended to be used instead. This more clearly expresses the
intent that the item is only visible within its own crate.
This lint is “allow” by default because it will trigger for a large amount of existing Rust code. Eventually it is desired for this to become warn-by-default.
unsafe-attr-outside-unsafe
The unsafe_attr_outside_unsafe lint detects a missing unsafe keyword
on attributes considered unsafe.
Example
extern "C"
Explanation
Some attributes (e.g. no_mangle, export_name, link_section – see
issue #82499 for a more complete list) are considered “unsafe” attributes.
An unsafe attribute must only be used inside unsafe(…).
This lint can automatically wrap the attributes in unsafe(...) , but this
obviously cannot verify that the preconditions of the unsafe
attributes are fulfilled, so that is still up to the user.
The lint is currently “allow” by default, but that might change in the future.
unsafe-code
The unsafe_code lint catches usage of unsafe code and other
potentially unsound constructs like no_mangle, export_name,
and link_section.
Example
pub static VAR1: u32 = 1;
Explanation
This lint is intended to restrict the usage of unsafe blocks and other
constructs (including, but not limited to no_mangle, link_section
and export_name attributes) wrong usage of which causes undefined
behavior.
unsafe-op-in-unsafe-fn
The unsafe_op_in_unsafe_fn lint detects unsafe operations in unsafe
functions without an explicit unsafe block.
Example
unsafe
unsafe
Explanation
Currently, an unsafe fn allows any unsafe operation within its
body. However, this can increase the surface area of code that needs
to be scrutinized for proper behavior. The unsafe block provides a
convenient way to make it clear exactly which parts of the code are
performing unsafe operations. In the future, it is desired to change
it so that unsafe operations cannot be performed in an unsafe fn
without an unsafe block.
The fix to this is to wrap the unsafe code in an unsafe block.
This lint is “allow” by default on editions up to 2021, from 2024 it is “warn” by default; the plan for increasing severity further is still being considered. See RFC #2585 and issue #71668 for more details.
unstable-features
The unstable_features lint detects uses of #![feature].
Example
Explanation
In larger nightly-based projects which
- consist of a multitude of crates where a subset of crates has to compile on
stable either unconditionally or depending on a
cfgflag to for example allow stable users to depend on them, - don’t use nightly for experimental features but for, e.g., unstable options only,
this lint may come in handy to enforce policies of these kinds.
unused-crate-dependencies
The unused_crate_dependencies lint detects crate dependencies that
are never used.
Example
This will produce:
error: extern crate `regex` is unused in crate `lint_example`
|
= help: remove the dependency or add `use regex as _;` to the crate root
note: the lint level is defined here
--> src/lib.rs:1:9
|
1 | #![deny(unused_crate_dependencies)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^
Explanation
After removing the code that uses a dependency, this usually also
requires removing the dependency from the build configuration.
However, sometimes that step can be missed, which leads to time wasted
building dependencies that are no longer used. This lint can be
enabled to detect dependencies that are never used (more specifically,
any dependency passed with the --extern command-line flag that is
never referenced via use, extern crate, or in any path).
This lint is “allow” by default because it can provide false positives depending on how the build system is configured. For example, when using Cargo, a “package” consists of multiple crates (such as a library and a binary), but the dependencies are defined for the package as a whole. If there is a dependency that is only used in the binary, but not the library, then the lint will be incorrectly issued in the library.
unused-extern-crates
The unused_extern_crates lint guards against extern crate items
that are never used.
Example
extern crate proc_macro;
Explanation
extern crate items that are unused have no effect and should be
removed. Note that there are some cases where specifying an extern crate is desired for the side effect of ensuring the given crate is
linked, even though it is not otherwise directly referenced. The lint
can be silenced by aliasing the crate to an underscore, such as
extern crate foo as _. Also note that it is no longer idiomatic to
use extern crate in the 2018 edition, as extern crates are now
automatically added in scope.
This lint is “allow” by default because it can be noisy, and produce
false-positives. If a dependency is being removed from a project, it
is recommended to remove it from the build configuration (such as
Cargo.toml) to ensure stale build entries aren’t left behind.
unused-import-braces
The unused_import_braces lint catches unnecessary braces around an
imported item.
Example
use ;
Explanation
If there is only a single item, then remove the braces (use test::A;
for example).
This lint is “allow” by default because it is only enforcing a stylistic choice.
unused-lifetimes
The unused_lifetimes lint detects lifetime parameters that are never
used.
Example
Explanation
Unused lifetime parameters may signal a mistake or unfinished code. Consider removing the parameter.
unused-macro-rules
The unused_macro_rules lint detects macro rules that were not used.
Note that the lint is distinct from the unused_macros lint, which
fires if the entire macro is never called, while this lint fires for
single unused rules of the macro that is otherwise used.
unused_macro_rules fires only if unused_macros wouldn’t fire.
Example
Explanation
Unused macro rules may signal a mistake or unfinished code. Furthermore, they slow down compilation. Right now, silencing the warning is not supported on a single rule level, so you have to add an allow to the entire macro definition.
If you intended to export the macro to make it
available outside of the crate, use the macro_export attribute.
unused-qualifications
The unused_qualifications lint detects unnecessarily qualified
names.
Example
Explanation
If an item from another module is already brought into scope, then
there is no need to qualify it in this case. You can call bar()
directly, without the foo::.
This lint is “allow” by default because it is somewhat pedantic, and doesn’t indicate an actual problem, but rather a stylistic choice, and can be noisy when refactoring or moving around code.
unused-results
The unused_results lint checks for the unused result of an
expression in a statement.
Example
Explanation
Ignoring the return value of a function may indicate a mistake. In
cases were it is almost certain that the result should be used, it is
recommended to annotate the function with the must_use attribute.
Failure to use such a return value will trigger the unused_must_use
lint which is warn-by-default. The unused_results lint is
essentially the same, but triggers for all return values.
This lint is “allow” by default because it can be noisy, and may not be
an actual problem. For example, calling the remove method of a Vec
or HashMap returns the previous value, which you may not care about.
Using this lint would require explicitly ignoring or discarding such
values.
variant-size-differences
The variant_size_differences lint detects enums with widely varying
variant sizes.
Example
Explanation
It can be a mistake to add a variant to an enum that is much larger than the other variants, bloating the overall size required for all variants. This can impact performance and memory usage. This is triggered if one variant is more than 3 times larger than the second-largest variant.
Consider placing the large variant’s contents on the heap (for example
via Box) to keep the overall size of the enum itself down.
This lint is “allow” by default because it can be noisy, and may not be an actual problem. Decisions about this should be guided with profiling and benchmarking.