Clippy lints · 847 lints · Clippy 0.1.99
Every Clippy lint, explained: fix it or allow it
Paste a cargo clippy warning to jump to its page: what it means, the real warning text, whether cargo clippy --fix handles it, and the exact line to allow it. Or set up your project's lints below.
The groups, and what they mean
| Group | Default | Lints | What it is for |
|---|---|---|---|
| Correctness | deny | 67 | Code that is almost certainly wrong. Denied by default: the build fails until you fix it or allow it. |
| Suspicious | warn | 85 | Code that is most likely wrong or useless. Warns by default. |
| Style | warn | 159 | Code that works but is not idiomatic Rust. Warns by default. |
| Complexity | warn | 144 | Code that does something simple in a complicated way. Warns by default. |
| Performance | warn | 38 | Code that could be written to run faster. Warns by default. |
| Pedantic | allow | 145 | Stricter lints with some false positives. Off by default; opt in with clippy::pedantic. |
| Restriction | allow | 135 | Lints that forbid language features for specific codebases (no unwrap, no indexing...). Off by default; pick them one by one, never the whole group. |
| Nursery | allow | 52 | New lints still being finished. Off by default and may have false positives. |
| Cargo | allow | 5 | Checks on Cargo.toml metadata. Off by default. |
| Deprecated | none | 17 | Removed or merged into another lint. Remove it from your config. |
Set up your lints
Lint config generator
Popular single lints
Groups get priority = -1 so single-lint lines override them; Cargo requires that when a group and one of its lints are both set.
Lints people look up most
- needless_returnunneeded `return` statement
- redundant_cloneChecks for a redundant clone() (and its relatives) which clones an owned value that is going to be dropped without further use
- unwrap_usedChecks for .unwrap() or .unwrap_err() calls on Results and .unwrap() call on Options
- too_many_argumentsChecks for functions with too many parameters
- new_without_defaultChecks for public types with a pub fn new() -> Self method and no implementation of Default
- len_zeroChecks for getting the length of something via .len() just to compare to zero, and suggests using .is_empty() where applicable
- clone_on_copyusing `clone` on type `u64` which implements the `Copy` trait
- needless_borrowthis expression creates a reference which is immediately dereferenced by the compiler
- module_name_repetitionsDetects public item names that are prefixed or suffixed by the containing public module’s name
- manual_mapmanual implementation of `Option::map`
- expect_usedChecks for .expect() or .expect_err() calls on Results and .expect() call on Options
- large_enum_variantlarge size difference between variants
- type_complexityChecks for types used in structs, parameters and let declarations above a certain complexity threshold
- too_many_linesChecks for functions with a large amount of lines
- cognitive_complexityWe used to think it measured how hard a method is to understand
- missing_errors_docChecks the doc comments of publicly visible functions that return a Result type and warns if there is no # Errors section
- must_use_candidateChecks for public functions that have no #[must_use] attribute, but return something not already marked must-use, have no mutable arg and mutate no statics
- uninlined_format_argsDetect when a variable is not inlined in a format string, and suggests to inline it
- needless_pass_by_valuethis argument is passed by value, but not consumed in the function body
- redundant_closureChecks for closures which just call another function where the function can be called directly
Correctness (67)
- absurd_extreme_comparisonsthis comparison involving the minimum or maximum element for this type contains a case that is always true or always false
- almost_swappedChecks for foo = bar; bar = foo sequences
- approx_constantapproximate value of `f{32, 64}::consts::PI` found
- async_yields_asyncan async construct yields a type which is itself awaitable
- bad_bit_maskChecks for incompatible bit masks in comparisons. The formula for detecting if an expression of the type _ <bit_op> m <cmp_op> c (where <bit_op> is one of {&, |} and <cmp_op> is one of {!=, >=, >, !=, >=, >}) can be determined from the following table: ComparisonBit OpExampleis alwaysFormula == or !=&x & 2 == 3falsec & m != c < or >=&x & 2 < 3truem < c > or <=&x & 1 > 1falsem <= c == or !=|x | 1 == 0falsec | m != c < or >=|x | 1 < 1falsem >= c <= or >|x | 1 > 0truem > c
- cast_slice_different_sizescasting between raw pointers to `[i32]` (element size 4) and `[u8]` (element size 1) does not adjust the count
- char_indices_as_byte_indicesChecks for usage of a character position yielded by .chars().enumerate() in a context where a byte index is expected, such as an argument to a specific str method or indexing into a str or String
- deprecated_semverthe since field must contain a semver-compliant version
- derive_ord_xor_partial_ordLints against manual PartialOrd and Ord implementations for types with a derived Ord or PartialOrd implementation
- derived_hash_with_manual_eqLints against manual PartialEq implementations for types with a derived Hash implementation
- eager_transmutethis transmute is always evaluated eagerly, even if the condition is false
- enum_clike_unportable_variantC-like enum variant discriminant is not portable to 32-bit targets
- eq_opChecks for equal operands to comparison, logical and bitwise, difference and division binary operators (==, >, etc., &&, ||, &, |, ^, - and /)
- erasing_opthis operation will always return zero. This is likely not the intended outcome
- if_let_mutexChecks for Mutex::lock calls in if let expression with lock calls in any of the else blocks
- ifs_same_condChecks for consecutive ifs with the same condition
- impl_hash_borrow_with_str_and_bytesthe semantics of `Borrow<T>` around `Hash` can't be satisfied when both `Borrow<str>` and `Borrow<[u8]>` are implemented
- impossible_comparisonsChecks for double comparisons that can never succeed
- ineffective_bit_maskChecks for bit masks in comparisons which can be removed without changing the outcome
- infinite_iterinfinite iteration detected
- inherent_to_string_shadow_displaytype `main::A` implements inherent method `to_string(&self) -> String` which shadows the implementation of `Display`
- inline_fn_without_bodyuse of `#[inline]` on trait method `name` which has no body
- invalid_regexChecks regex creation (with Regex::new, RegexBuilder::new, or RegexSet::new) for correct regex syntax
- inverted_saturating_subinverted arithmetic check before subtraction
- invisible_charactersChecks for invisible Unicode characters in the code
- iter_next_loopChecks for loops on x.next()
- iter_skip_zerousage of `.skip(0)`
- iterator_step_by_zero`Iterator::step_by(0)` will panic at runtime
- let_underscore_lockChecks for let _ = sync_lock
- lint_groups_priorityChecks for lint groups with the same priority as lints in the Cargo.toml [lints] table. This lint will be removed once cargo#12918 is resolved
- match_str_case_mismatchChecks for match expressions modifying the case of a string with non-compliant arms
- mem_replace_with_uninitChecks for mem::replace(&mut _, mem::uninitialized()) and mem::replace(&mut _, mem::zeroed())
- min_maxChecks for expressions where std::cmp::min and max are used to clamp values, but switched so that the result is constant
- mistyped_literal_suffixesWarns for mistyped suffix in literals
- modulo_oneChecks for getting the remainder of integer division by one or minus one
- mut_from_refThis lint checks for functions that take immutable references and return mutable ones
- never_loopthis loop never actually loops
- non_octal_unix_permissionsChecks for non-octal values used to set Unix file permissions
- nonsensical_open_optionsChecks for duplicate open options as well as combinations that make no sense
- not_unsafe_ptr_arg_derefthis public function might dereference a raw pointer but is not marked `unsafe`
- option_env_unwrapthis will panic at run-time if the environment variable doesn't exist at compile-time
- out_of_bounds_indexingindex is out of bounds
- panicking_overflow_checksDetects C-style underflow/overflow checks
- panicking_unwrapChecks for calls of unwrap[_err]() that will always fail
- possible_missing_commapossibly missing a comma here
- read_line_without_trimcalling `.parse()` on a string without trimming the trailing newline character
- recursive_format_implusing `self.to_string` in `fmt::Display` implementation will cause infinite recursion
- redundant_comparisonsChecks for ineffective double comparisons against constants
- reversed_empty_rangesthis range is empty so it will yield no values
- self_assignmentself-assignment of `a.x` to `a.x`
- serde_api_misuseChecks for misuses of the serde API
- size_of_in_element_countDetects expressions where size_of::<T> or size_of_val::<T> is used as a count of elements of type T
- suspicious_splitnChecks for calls to [splitn] (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and related functions with either zero or one splits
- transmute_null_to_fntransmuting a known null pointer into a function pointer
- transmuting_nulltransmuting a known null pointer into a reference
- uninit_assumed_initthis call for this type may be undefined behavior
- uninit_vecChecks for set_len() call that creates Vec with uninitialized elements. This is commonly caused by calling set_len() right after allocating or reserving a buffer with new(), default(), with_capacity(), or reserve()
- unit_cmpChecks for comparisons to unit
- unit_hashDetects ().hash(_)
- unit_return_expecting_ordthis closure returns the unit type which also implements Ord
- unsound_collection_transmutetransmute from `std::vec::Vec<u16>` to `std::vec::Vec<u32>` with mismatched layout is unsound
- unused_io_amountwritten amount is not handled
- useless_attributeChecks for extern crate and use items annotated with lint attributes. This lint permits lint attributes for lints emitted on the items themself. For use items these lints are: ambiguous_glob_reexports dead_code deprecated hidden_glob_reexports unreachable_pub unused unused_braces unused_import_braces clippy::disallowed_types clippy::enum_glob_use clippy::macro_use_imports clippy::module_name_repetitions clippy::redundant_pub_crate clippy::single_component_path_imports clippy::unsafe_removed_from_name clippy::wildcard_imports For extern crate items these lints are: unused_imports on items with #[macro_use]
- vec_resize_to_zeroFinds occurrences of Vec::resize(0, an_int)
- while_immutable_conditionvariables in the condition are not mutated in the loop body
- wrong_transmuteChecks for transmutes that can’t ever be correct on any architecture
- zst_offsetoffset calculation on zero-sized value
Suspicious (85)
- almost_complete_rangealmost complete ascii range
- arc_with_non_send_syncarc with non send sync
- await_holding_invalid_typeAllows users to configure types which should not be held across await suspension points
- await_holding_lockChecks for calls to await while holding a non-async-aware MutexGuard
- await_holding_refcell_refChecks for calls to await while holding a RefCell, Ref, or RefMut
- blanket_clippy_restriction_lints`clippy::restriction` is not meant to be enabled as a group
- block_scrutineeWarns when a match, if let, or while let scrutinee is wrapped in a block. This lint only triggers on the 2021 edition and older
- by_ref_peekable_peekcalling `.by_ref().peekable().peek()` will advance the underlying iterator and consume its first output
- cast_abs_to_unsignedcasting the result of `i32::abs()` to u32
- cast_enum_constructorcast of an enum tuple constructor to an integer
- cast_enum_truncationcasting `main::E::X` to `u8` will truncate the value
- cast_nan_to_intcasting a known NaN to u64
- cast_slice_from_raw_partsChecks for a raw slice being cast to a slice pointer
- confusing_method_to_numeric_castcasting function pointer `u16::max` to `usize`
- const_is_emptythis expression always evaluates to true
- crate_in_macro_def`crate` references the macro call's crate
- crosspointer_transmuteChecks for transmutes between a type T and *T
- declare_interior_mutable_constnamed constant with interior mutability
- deprecated_clippy_cfg_attr`feature = "cargo-clippy"` was replaced by `clippy`
- doc_nested_refdefslink reference defined in list item
- doc_suspicious_footnoteslooks like a footnote ref, but has no matching footnote
- drop_non_dropcall to `std::mem::drop` with a value that does not implement `Drop`. Dropping such a type only extends its contained lifetimes
- duplicate_modfile is loaded as a module multiple times: `main.rs`
- duplicated_attributesduplicated attribute
- empty_docsempty doc comment
- empty_line_after_doc_commentsempty line after doc comment
- empty_line_after_outer_attrempty line after outer attribute
- empty_loopempty `loop {}` wastes CPU cycles
- float_equality_without_absfloat equality check without `.abs()`
- for_unbounded_rangefor loop on unbounded range
- forget_non_dropcall to `std::mem::forget` with a value that does not implement `Drop`. Forgetting such a type is the same as dropping it
- four_forward_slashesthis item has comments with 4 forward slashes (`////`). These look like doc comments, but they aren't
- from_raw_with_void_ptrChecks if we’re passing a c_void raw pointer to {Box,Rc,Arc,Weak}::from_raw(_)
- incompatible_msrvThis lint checks that no function newer than the defined MSRV (minimum supported rust version) is used in the crate
- ineffective_open_optionsChecks if both .write(true) and .append(true) methods are called on a same OpenOptions
- infallible_try_frominfallible TryFrom impl; consider implementing From instead
- iter_out_of_boundsthis `.take()` call takes more items than the iterator will produce
- join_absolute_pathsChecks for calls to Path::join that start with a path separator (\\ or /)
- let_underscore_futurenon-binding `let` on a future
- lines_filter_map_okChecks for usage of lines.filter_map(Result::ok) or lines.flat_map(Result::ok) when lines has type std::io::Lines
- macro_metavars_in_unsafeLooks for macros that expand metavariables in an unsafe block
- manual_unwrap_or_defaultmatch can be simplified with `.unwrap_or_default()`
- mismatched_bit_width_typepossible buggy implementation of `bit_width`
- misnamed_gettersgetter function appears to return the wrong field
- misrefactored_assign_opvariable appears on both sides of an assignment operation
- missing_transmute_annotationsChecks if transmute calls have all generics specified
- multi_assignmentsassignments don't nest intuitively
- mut_range_boundattempt to mutate range bound within loop
- mutable_key_typeChecks for sets/maps with mutable key types
- needless_character_iterationchecking if a string is ascii using iterators
- needless_maybe_sized`?Sized` bound is ignored because of a `Sized` requirement
- no_effect_replacereplacing text with itself
- non_canonical_clone_implnon-canonical implementation of `clone` on a `Copy` type
- non_canonical_partial_ord_implChecks for non-canonical implementations of PartialOrd when Ord is already implemented
- octal_escapesoctal-looking escape in a literal
- path_ends_with_extLooks for calls to Path::ends_with calls where the argument looks like a file extension. By default, Clippy has a short list of known filenames that start with a dot but aren’t necessarily file extensions (e.g
- permissions_set_readonly_falsecall to `set_readonly` with argument `false`
- pointers_in_nomem_asm_blockpassing pointers to nomem asm block
- possible_missing_elsethis looks like an `else {..}` but the `else` is missing
- print_in_format_impluse of `println!` in `Display` impl
- rc_clone_in_vec_initinitializing a reference-counted pointer in `vec![elem; len]`
- redundant_localsredundant redefinition of a binding `a`
- repeat_vec_with_capacityLooks for patterns such as vec![Vec::with_capacity(x); n] or iter::repeat(Vec::with_capacity(x))
- repr_packed_without_abiitem uses `packed` representation without ABI-qualification
- single_range_in_vec_initan array of `Range` that is only one element
- size_of_refargument to `size_of_val()` is a reference to a reference
- suspicious_arithmetic_implLints for suspicious operations in impls of arithmetic operators, e.g. subtracting elements in an Add impl
- suspicious_assignment_formattingthis looks like you are trying to use `.. -= ..`, but you really are doing `.. = (- ..)`
- suspicious_command_arg_spacesingle argument that looks like it should be multiple arguments
- suspicious_doc_commentsthis is an outer doc comment and does not apply to the parent module or crate
- suspicious_else_formattingthis is an `else {..}` but the formatting might hide it
- suspicious_mapthis call to `map()` won't have an effect on the call to `count()`
- suspicious_op_assign_implLints for suspicious operations in impls of OpAssign, e.g. subtracting elements in an AddAssign impl
- suspicious_open_optionsChecks for the suspicious use of OpenOptions::create() without an explicit OpenOptions::truncate()
- suspicious_to_ownedChecks for the usage of _.to_owned(), on a Cow<'_, _>
- suspicious_unary_op_formattingby not having a space between `&&` and `!` it looks like `&&!` is a single operator
- swap_ptr_to_refcall to `core::mem::swap` with a parameter derived from a raw pointer
- test_attr_in_doctestunit tests in doctest are not executed
- type_id_on_boxcalling `.type_id()` on `Box<dyn Any>`
- unconditional_recursionfunction cannot return without recursing
- unnecessary_clippy_cfgno need to put clippy lints behind a `clippy` cfg
- unnecessary_option_map_or_elseunused "map closure" when calling `Option::map_or_else` value
- unnecessary_result_map_or_elseChecks for usage of .map_or_else() “map closure” for Result type
- zero_repeat_side_effectsexpression with side effects as the initial value in a zero-sized array initializer
- zombie_processesspawned process is never `wait()`ed on
Style (159)
- assertions_on_constantsChecks for assert!(true) and assert!(false) calls
- assign_op_patternmanual implementation of an assign operation
- blocks_in_conditionsChecks for if and match conditions that use blocks containing an expression, statements or conditions that use closures with blocks
- bool_assert_comparisonused `assert_eq!` with a literal bool
- borrow_interior_mutable_constborrow of a named constant with interior mutability
- box_default`Box::new(_)` of default value
- builtin_type_shadowthis generic shadows the built-in type `u32`
- byte_char_slicescan be more succinctly written as a byte str
- bytes_nthcalled `.bytes().nth()` on a `str`
- chars_last_cmpChecks for usage of _.chars().last() or _.chars().next_back() on a str to check if it ends with a given char
- chars_next_cmpyou should use the `starts_with` method
- chunks_exact_to_as_chunksusing `chunks_exact` with a constant chunk size
- cmp_nullThis lint checks for equality comparisons with ptr::null or ptr::null_mut
- collapsible_ifChecks for nested if statements which can be collapsed by &&-combining their conditions
- collapsible_matchthis `match` can be collapsed into the outer `match`
- comparison_to_emptyChecks for comparing to an empty slice such as "" or [], and suggests using .is_empty() where applicable
- default_instead_of_iter_empty`std::iter::empty()` is the more idiomatic way
- disallowed_fieldsDenies the configured fields in clippy.toml Note: Even though this lint is warn-by-default, it will only trigger if fields are defined in the clippy.toml file
- disallowed_macrosDenies the configured macros in clippy.toml Note: Even though this lint is warn-by-default, it will only trigger if macros are defined in the clippy.toml file
- disallowed_methodsDenies the configured methods and functions in clippy.toml Note: Even though this lint is warn-by-default, it will only trigger if methods are defined in the clippy.toml file
- disallowed_namesuse of a disallowed/placeholder name `foo`
- disallowed_typesDenies the configured types in clippy.toml. Note: Even though this lint is warn-by-default, it will only trigger if types are defined in the clippy.toml file
- doc_lazy_continuationdoc quote line without `>` marker
- doc_overindented_list_itemsDetects overindented list items in doc comments where the continuation lines are indented more than necessary
- double_must_usethis function has a `#[must_use]` attribute with no message, but returns a type already considered as `#[must_use]`
- duplicate_underscore_argument`a` already exists, having another argument having almost the same name makes code comprehension and documentation more difficult
- enum_variant_namesvariant name ends with the enum's name
- err_expectcalled `.err().expect()` on a `Result` value
- excessive_precisionfloat has excessive precision
- field_reassign_with_defaultChecks for immediate reassignment of fields initialized with Default::default()
- filter_map_bool_thenChecks for usage of bool::then in Iterator::filter_map
- fn_to_numeric_castcasting function pointer `fun` to `i64`
- fn_to_numeric_cast_with_truncationcasting function pointer `fn1` to `i32`, which truncates the value
- for_kv_mapChecks for iterating a map (HashMap or BTreeMap) and ignoring either the keys or values
- from_over_intoan implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true
- from_str_radix_10Checks for function invocations of the form primitive::from_str_radix(s, 10)
- get_firstaccessing first element with `x.get(0)`
- if_same_then_elseChecks for if/else with the same body as the then part and the else part
- implicit_saturating_addmanual saturating add detected
- implicit_saturating_subChecks for implicit saturating subtraction
- inconsistent_digit_groupingdigits grouped inconsistently by underscores
- infallible_destructuring_matchyou seem to be trying to use `match` to destructure a single infallible pattern
- inherent_to_stringimplementation of inherent method `to_string(&self) -> String` for type `main::A`
- init_numbered_fieldsused a field initializer for a tuple struct
- into_iter_on_refChecks for into_iter calls on references which should be replaced by iter or iter_mut
- io_other_errorthis can be `std::io::Error::other(_)`
- is_digit_ascii_radixuse of `char::is_digit` with literal radix of 10
- items_after_test_moduleTriggers if an item is declared after the testing module marked with #[cfg(test)]
- iter_cloned_collectcalled `.iter().cloned().collect()` on a slice to create a `Vec`
- iter_next_sliceChecks for usage of iter().next() or iter_mut().next() on a Slice or an Array
- iter_nthcalled `.iter().nth()` on a `Vec`
- iter_nth_zeroChecks for the use of iter.nth(0)
- iter_skip_nextcalled `skip(..).next()` on an iterator
- just_underscores_and_digitsconsider choosing a more descriptive name
- legacy_numeric_constantsusage of a legacy numeric constant
- len_without_is_emptyChecks for items that implement .len() but not .is_empty()
- len_zeroChecks for getting the length of something via .len() just to compare to zero, and suggests using .is_empty() where applicable
- let_and_returnreturning the result of a `let` binding from a block
- let_unit_valuethis let-binding has unit value
- main_recursionrecursing into entrypoint `main`
- manual_async_fnthis function can be simplified using the `async fn` syntax
- manual_bitsusage of `size_of::<T>()` to obtain the size of `T` in bits
- manual_dangling_ptrmanual creation of a dangling pointer
- manual_is_ascii_checkmanual check for common ascii range
- manual_is_finiteChecks for manual is_finite reimplementations (i.e., x != <float>::INFINITY && x != <float>::NEG_INFINITY)
- manual_is_infiniteChecks for manual is_infinite reimplementations (i.e., x == <float>::INFINITY || x == <float>::NEG_INFINITY)
- manual_mapmanual implementation of `Option::map`
- manual_next_backChecks for .rev().next() on a DoubleEndedIterator
- manual_non_exhaustiveChecks for manual implementations of the non-exhaustive pattern
- manual_ok_orthis pattern reimplements `Option::ok_or`
- manual_pattern_char_comparisonthis manual char comparison can be written more succinctly
- manual_range_containsmanual `Range::contains` implementation
- manual_repeat_nthis `repeat().take()` can be written more concisely
- manual_rotatethere is no need to manually implement bit rotation
- manual_saturating_arithmeticChecks for .checked_add/sub(x).unwrap_or(MAX/MIN)
- manual_slice_fillmanually filling a slice
- manual_while_let_someyou seem to be trying to pop elements from a `Vec` in a loop
- map_cloneyou are using an explicit closure for copying elements
- map_collect_result_unit`.map().collect()` can be replaced with `.try_for_each()`
- match_like_matches_macromatch expression looks like `matches!` macro
- match_overlapping_armsome ranges overlap
- match_ref_patsChecks for matches where all arms match a reference, suggesting to remove the reference and deref the matched expression instead
- match_result_okChecks for unnecessary ok() in while let
- mem_replace_option_with_nonereplacing an `Option` with `None`
- mem_replace_option_with_somereplacing an `Option` with `Some(..)`
- mem_replace_with_defaultreplacing a value of type `T` with `T::default()`
- missing_enforced_import_renamesChecks for imports that do not rename the item as specified in the enforced-import-renames config option. Note: Even though this lint is warn-by-default, it will only trigger if import renames are defined in the clippy.toml file
- missing_safety_docChecks for the doc comments of publicly visible unsafe functions and warns if there is no # Safety section
- mixed_attributes_styleChecks for items that have the same kind of attributes with mixed styles (inner/outer)
- mixed_case_hex_literalsinconsistent casing in hexadecimal literal
- module_inceptionChecks for modules that have the same name as their parent module
- multiple_bound_locationsbound is defined in more than one place
- must_use_unitthis unit-returning function has a `#[must_use]` attribute
- mut_mutex_lockcalling `&mut Mutex::lock` unnecessarily locks an exclusive (mutable) reference
- needless_borrowthis expression creates a reference which is immediately dereferenced by the compiler
- needless_borrows_for_generic_argsthe borrowed expression implements the required traits
- needless_doctest_mainChecks for fn main() {
- needless_elsethis `else` branch is empty
- needless_late_initunneeded late initialization
- needless_parens_on_range_literalsneedless parenthesis on range literals can be removed
- needless_pub_selfunnecessary `pub(self)`
- needless_range_loopthe loop variable `i` is only used to index `vec`
- needless_returnunneeded `return` statement
- needless_return_with_question_markChecks for return statements on Err paired with the ? operator
- neg_multiplyChecks for multiplication by -1 as a form of negation
- new_ret_no_selfChecks for new not returning a type that contains Self
- new_without_defaultChecks for public types with a pub fn new() -> Self method and no implementation of Default
- non_minimal_cfgunneeded sub `cfg` when there is only one condition
- nonstandard_macro_bracesuse of irregular braces for `vec!` macro
- obfuscated_if_elsethis method chain can be written more clearly with `if .. else ..`
- ok_expectChecks for usage of ok().expect(..). Note: This lint only triggers for code marked compatible with versions of the compiler older than Rust 1.82.0
- op_refChecks for arguments to == which have their address taken to satisfy a bound and suggests to dereference the other argument instead
- option_map_or_noneChecks for usage of _.map_or(None, _)
- owned_cowneedlessly owned Cow type
- partialeq_to_nonebinary comparison to literal `Option::None`
- print_literalliteral with an empty format string
- print_with_newlineThis lint warns when you use print!() with a format string that ends in a newline
- println_empty_stringempty string literal in `println!`
- ptr_argThis lint checks for function arguments of type &String, &Vec, &PathBuf, and Cow<_>
- ptr_equse `std::ptr::eq` when comparing raw pointers
- question_markChecks for expressions that could be replaced by the ? operator
- redundant_closureChecks for closures which just call another function where the function can be called directly
- redundant_field_namesredundant field names in struct initialization
- redundant_patternthe `y @ _` pattern can be written as just `y`
- redundant_pattern_matchingLint for redundant pattern matching over Result, Option, std::task::Poll, std::net::IpAddr or bools
- redundant_static_lifetimesconstants have by default a `'static` lifetime
- result_map_or_into_optionChecks for usage of _.map_or(None, Some)
- result_unit_errthis returns a `Result<_, ()>`
- same_item_pushit looks like the same item is being pushed into this `Vec`
- self_named_constructorsconstructor `foo` has the same name as the type
- should_implement_traitChecks for methods that should live in a trait implementation of a std trait (see llogiq’s blog post for further information) instead of an inherent implementation
- single_char_add_strWarns when using push_str/insert_str with a single-character string literal where push/insert with a char would work fine
- single_component_path_importsthis import is redundant
- single_matchChecks for matches with a single arm where an if let will usually suffice. This intentionally does not lint if there are comments inside of the other arm, so as to allow the user to document why having another explicit pattern with an empty body is necessary, or because the comments need to be preserved for other reasons
- string_extend_charscalling `.extend(_.chars())`
- tabs_in_doc_commentsusing tabs in doc comments is not recommended
- to_digit_is_someChecks for .to_digit(..).is_some() on chars
- to_string_trait_impldirect implementation of `ToString`
- toplevel_ref_arg`ref` directly on a function parameter does not prevent taking ownership of the passed argument. Consider using a reference type instead
- trim_split_whitespacefound call to `str::trim` before `str::split_whitespace`
- unnecessary_fallible_conversionsuse of a fallible conversion when an infallible one could be used
- unnecessary_foldthis `.fold` can be written more succinctly using another method
- unnecessary_lazy_evaluationsunnecessary closure used to substitute value for `Option::None`
- unnecessary_map_orthis `map_or` can be simplified
- unnecessary_mut_passedDetects passing a mutable reference to a function that only requires an immutable reference
- unnecessary_owned_empty_stringsusage of `&String::new()` for a function expecting a `&str` argument
- unneeded_struct_patternstruct pattern is not needed for a unit variant
- unsafe_removed_from_nameChecks for imports that remove “unsafe” from an item’s name
- unused_enumerate_indexyou seem to use `.enumerate()` and immediately discard the index
- unused_unitunneeded unit expression
- unusual_byte_groupingsWarns if hexadecimal or binary literals are not grouped by nibble or byte
- unwrap_or_defaultChecks for usages of the following functions with an argument that constructs a default value (e.g., Default::default or String::new): unwrap_or unwrap_or_else or_insert or_insert_with
- upper_case_acronymsChecks for fully capitalized names and optionally names containing a capitalized acronym
- while_let_on_iteratorChecks for while let expressions on iterators
- write_literalThis lint warns about the use of literals as write!/writeln! args
- write_with_newlineThis lint warns when you use write!() with a format string that ends in a newline
- writeln_empty_stringThis lint warns when you use writeln!(buf, "") to print a newline
- wrong_self_conventionChecks for methods with certain name prefixes or suffixes, and which do not adhere to standard conventions regarding how self is taken. The actual rules are: PrefixPostfixself takenself type as_none&self or &mut selfany from_nonenoneany into_noneselfany is_none&mut self or &self or noneany to__mut&mut selfany to_not _mutselfCopy to_not _mut&selfnot Copy Note: Clippy doesn’t trigger methods with to_ prefix in: Traits definition. Clippy can not tell if a type that implements a trait is Copy or not. Traits implementation, when &self is taken. The method signature is controlled by the trait and often &self is required for all types that implement the trait (see e.g
- zero_ptr`0 as *const _` detected
Complexity (144)
- bind_instead_of_mapChecks for usage of _.and_then(|x| Some(y)), _.and_then(|x| Ok(y)) or _.or_else(|x| Err(y))
- bool_comparisonChecks for expressions of the form x == true, x != true and order comparisons such as x < true (or vice versa) and suggest using the variable directly
- borrow_deref_refderef on an immutable reference
- borrowed_boxChecks for usage of &Box<T> anywhere in the code. Check the Box documentation for more information
- bytes_count_to_lenusing long and hard to read `.bytes().count()`
- char_lit_as_u8Checks for expressions where a character literal is cast to u8 and suggests using a byte literal instead
- clone_on_copyusing `clone` on type `u64` which implements the `Copy` trait
- default_constructed_unit_structsChecks for construction on unit struct using default
- deprecated_cfg_attr`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes
- deref_addrofChecks for usage of *& and *&mut in expressions
- derivable_implsthis `impl` can be derived
- diverging_sub_expressionChecks for diverging calls that are not match arms or statements
- double_comparisonsChecks for double comparisons that could be simplified to a single expression
- double_parensunnecessary parentheses
- duration_subsecChecks for calculation of subsecond microseconds or milliseconds from other Duration methods
- excessive_nestingChecks for blocks which are nested beyond a certain threshold. Note: Even though this lint is warn-by-default, it will only trigger if a maximum nesting level is defined in the clippy.toml file
- explicit_auto_derefderef which would be done by auto-deref
- explicit_counter_loopChecks for loops over slices with an explicit counter and suggests the use of .enumerate()
- explicit_writeChecks for usage of write!() / writeln()! which can be replaced with (e)print!() / (e)println!()
- extra_unused_lifetimesthis lifetime isn't used in the function definition
- extra_unused_type_parametersChecks for type parameters in generics that are never used anywhere else
- filter_map_identityChecks for usage of filter_map(|x| x)
- filter_nextChecks for usage of _.filter(_).next()
- flat_map_identityChecks for usage of flat_map(|x| x)
- get_last_with_lenaccessing last element with `x.get(x.len() - 1)`
- identity_opChecks for identity operations, e.g., x + 0
- implied_bounds_in_implsLooks for bounds in impl Trait in return position that are implied by other bounds. This can happen when a trait is specified that another trait already has as a supertrait (e.g
- inspect_for_eachcalled `inspect(..).for_each(..)` on an `Iterator`
- int_plus_oneunnecessary `>= y + 1` or `x - 1 >=`
- iter_countcalled `.iter().count()` on a `Vec`
- iter_kv_mapChecks for iterating a map (HashMap or BTreeMap) and ignoring either the keys or values
- let_with_type_underscorevariable declared with type underscore
- manual_abs_diffDetects patterns like if a > b { a - b } else { b - a } and suggests using a.abs_diff(b)
- manual_c_str_literalsChecks for the manual creation of C strings (a string with a NUL byte at the end), either through one of the CStr constructor functions, or more plainly by calling .as_ptr() on a (byte) string literal with a hardcoded \0 byte at the end
- manual_checked_opsDetects manual zero checks before dividing integers, such as if x != 0 { y / x }
- manual_clampIdentifies good opportunities for a clamp function from std or core, and suggests using it
- manual_div_ceilChecks for an expression like (x + (y - 1)) / y which is a common manual reimplementation of x.div_ceil(y)
- manual_filtermanual implementation of `Option::filter`
- manual_filter_map`filter(..).map(..)` can be simplified as `filter_map(..)`
- manual_findmanual implementation of `Iterator::find`
- manual_find_map`find(..).map(..)` can be simplified as `find_map(..)`
- manual_flattenunnecessary `if let` since only the `Some` variant of the iterator element is used
- manual_hash_onemanual implementation of `BuildHasher::hash_one`
- manual_inspectusing `map` over `inspect`
- manual_is_multiple_ofChecks for manual implementation of .is_multiple_of() on unsigned integer types
- manual_isolate_lowest_onemanual implementation of `isolate_lowest_one`
- manual_main_separator_strtaking a reference on `std::path::MAIN_SEPARATOR` conversion to `String`
- manual_noop_wakerChecks for manual implementations of std::task::Wake that are empty
- manual_ok_errChecks for manual implementation of .ok() or .err() on Result values
- manual_option_as_sliceThis detects various manual reimplementations of Option::as_slice
- manual_option_zipmanual implementation of `Option::zip`
- manual_pop_ifChecks for code to be replaced by pop_if methods
- manual_range_patternsthis OR pattern can be rewritten using a range
- manual_rem_euclidmanual `rem_euclid` implementation
- manual_slice_size_calculationWhen a is &[T], detect a.len() * size_of::<T>() and suggest size_of_val(a) instead
- manual_split_onceChecks for usage of str::splitn(2, _)
- manual_stripstripping a prefix manually
- manual_swapthis looks like you are swapping `b` and `a` manually
- manual_takemanual implementation of `mem::take`
- manual_unwrap_orthis pattern reimplements `Option::unwrap_or`
- map_all_any_identityChecks for usage of .map(…), followed by .all(identity) or .any(identity)
- map_flattencalled `map(..).flatten()` on `Iterator`
- map_identityunnecessary map of the identity function
- map_or_identityexpression can be simplified using `Option::unwrap_or()`
- match_as_refmanual implementation of `Option::as_ref`
- match_single_bindingChecks for useless match that binds to only one value
- needless_arbitrary_self_typethe type of the `self` parameter does not need to be arbitrary
- needless_as_bytesneedless call to `as_bytes`
- needless_boolChecks for expressions of the form if c { true } else { false } (or vice versa) and suggests using the condition directly
- needless_bool_assignChecks for expressions of the form if c { x = true } else { x = false } (or vice versa) and suggest assigning the variable directly from the condition
- needless_borrowed_referencethis pattern takes a reference on something that is being dereferenced
- needless_ifsChecks for empty if branches with no else branch
- needless_lifetimesthe following explicit lifetimes could be elided: 'a
- needless_matchChecks for unnecessary match or match-like if let returns for Option and Result when function signatures are the same
- needless_option_as_derefderefed type is same as origin
- needless_option_takecalled `Option::take()` on a temporary value
- needless_question_markSuggests replacing Ok(x?) or Some(x?) with x in return positions where the ? operator is not needed to convert the type of x
- needless_splitnunnecessary use of `splitn`
- needless_updateChecks for needlessly including a base struct on update when all fields are changed anyway. This lint is not applied to structs marked with non_exhaustive
- neg_cmp_op_on_partial_ordthe use of negated comparison operators on partially ordered types produces code that is hard to read and refactor, please consider using the `partial_cmp` method instead, to make it clear that the two values could be incomparable
- no_effectstatement with no effect
- nonnull_unchecked_on_box_ptruse of `NonNull::new_unchecked` with `Box::into_raw`
- only_used_in_recursionparameter is only used in recursion
- option_as_ref_derefChecks for usage of _.as_ref().map(Deref::deref) or its aliases (such as String::as_str)
- option_filter_map`filter` for `Some` followed by `unwrap`
- option_map_unit_fnChecks for usage of option.map(f) where f is a function or closure that returns the unit type ()
- or_then_unwrapChecks for .or(…).unwrap() calls to Options and Results
- partialeq_ne_implre-implementing `PartialEq::ne` is unnecessary
- precedenceChecks for operations where precedence may be unclear and suggests to add parentheses. It catches a mixed usage of arithmetic and bit shifting/combining operators, as well as method calls applied to closures
- ptr_offset_with_castuse of `offset` with a `usize` cast to an `isize`
- range_zip_with_lenChecks for zipping a collection with the range of 0.._.len()
- redundant_as_strChecks for usage of as_str() on a String chained with a method available on the String itself
- redundant_async_blockthis async expression only awaits a single future
- redundant_at_rest_patternusing a rest pattern to bind an entire slice to a local
- redundant_closure_calltry not to call a closure in the expression where it is declared
- redundant_guardsChecks for unnecessary guards in match expressions
- redundant_slicingredundant slicing of the whole range
- repeat_oncecalling `repeat(1)` on a string literal
- reserve_after_initializationcall to `reserve` immediately after creation
- result_filter_map`filter` for `Ok` followed by `unwrap`
- result_map_unit_fnChecks for usage of result.map(f) where f is a function or closure that returns the unit type ()
- seek_from_currentusing `SeekFrom::Current` to start from current position
- seek_to_start_instead_of_rewindChecks for jumps to the start of a stream that implements Seek and uses the seek method providing Start as parameter
- short_circuit_statementChecks for the use of short circuit boolean conditions as a statement
- single_element_loopfor loop over a single element
- skip_while_nextChecks for usage of _.skip_while(condition).next()
- some_filteruse of `Some(x).filter(|_| predicate)`
- string_from_utf8_as_bytescalling a slice of `as_bytes()` with `from_utf8` should be not necessary
- strlen_on_c_stringsChecks for usage of libc::strlen on a CString or CStr value, and suggest calling count_bytes() instead
- swap_with_temporaryswapping with a temporary value is inefficient
- temporary_assignmentassignment to temporary
- too_many_argumentsChecks for functions with too many parameters
- transmute_bytes_to_strtransmute from a `&[u8]` to a `&str`
- transmute_int_to_booltransmute from a `u8` to a `bool`
- transmute_int_to_non_zeroChecks for transmutes from T to NonZero<T>, and suggests the new_unchecked method instead
- transmute_ptr_to_refChecks for transmutes from a pointer to a reference
- transmutes_expressible_as_ptr_castsChecks for transmutes that could be a pointer cast
- type_complexityChecks for types used in structs, parameters and let declarations above a certain complexity threshold
- unit_argChecks for passing a unit value as an argument to a function without using a unit literal (())
- unnecessary_castcasting integer literal to `i32` is unnecessary
- unnecessary_filter_mapthis `.filter_map(..)` can be written more simply using `.filter(..)`
- unnecessary_find_mapthis `.find_map(..)` can be written more simply using `.find(..)`
- unnecessary_first_then_checkunnecessary use of `first().is_none()` to check if slice is empty
- unnecessary_get_then_checkChecks the usage of .get().is_some() or .get().is_none() on std map types
- unnecessary_literal_unwrapused `unwrap()` on `Some` value
- unnecessary_map_on_constructorSuggests removing the use of a map() (or map_err()) method when an Option or Result is being constructed
- unnecessary_min_or_max`0` is never greater than `7_u32` and has therefore no effect
- unnecessary_operationChecks for expression statements that can be reduced to a sub-expression
- unnecessary_sort_byChecks for usage of Vec::sort_by passing in a closure which compares the two arguments, either directly or indirectly
- unnecessary_unwrapChecks for calls of unwrap[_err]() that cannot fail
- unnecessary_unwrap_uncheckedusage of `unwrap_unchecked` when an `_unchecked` variant of the function exists
- unneeded_wildcard_patternthis pattern is unneeded as the `..` pattern can match that element
- unused_format_specsformat specifiers have no effect on `format_args!()`
- useless_asrefChecks for usage of .as_ref() or .as_mut() where the types before and after the call are the same
- useless_concatunneeded use of `concat!` macro
- useless_conversionuseless conversion to the same type: `std::string::String`
- useless_formatuseless use of `format!`
- useless_nonzero_new_unchecked`NonZeroUsize::new()` and `Option::unwrap()` can be safely used in a `const` context
- useless_transmuteChecks for transmutes to the original type of the object and transmutes that could be a cast
- vec_box`Vec<T>` is already on the heap, the boxing is unnecessary
- while_let_loopthis loop could be written as a `while let` loop
- wildcard_in_or_patternsChecks for wildcard pattern used with others patterns in same match arm
- zero_divided_by_zeroconstant division of `0.0` with `0.0` will always result in NaN
- zero_prefixed_literalthis is a decimal constant
Performance (38)
- box_collectionChecks for usage of Box<T> where T is a collection such as Vec anywhere in the code. Check the Box documentation for more information
- boxed_locallocal variable doesn't need to be boxed here
- cloned_ref_to_slice_refsChecks for slice references with cloned references such as &[f.clone()]
- cmp_ownedChecks for conversions to owned values just for the sake of a comparison
- collapsible_str_replaceChecks for consecutive calls to str::replace (2 or more) that can be collapsed into a single call
- double_ended_iterator_lastcalled `Iterator::last` on a `DoubleEndedIterator`; this will needlessly iterate the entire iterator
- drain_collectdraining all elements of a collection into a new collection of the same type
- expect_fun_callChecks for calls to .expect(&format!(...)), .expect(foo(..)), etc., and suggests to use unwrap_or_else instead
- extend_with_drainuse of `extend` instead of `append` for adding the full range of a second vector
- format_in_format_argsDetects format! within the arguments of another macro that does formatting such as format! itself, write! or println!
- iter_overeager_clonedChecks for usage of _.cloned().<func>() where call to .cloned() can be postponed
- large_const_arraysChecks for large const arrays that should be defined as static instead
- large_enum_variantlarge size difference between variants
- manual_cleartruncating to zero length
- manual_containsusing `contains()` instead of `iter().any()` is more efficient
- manual_ignore_case_cmpmanual case-insensitive ASCII comparison
- manual_memcpyChecks for for-loops that manually copy items between slices that could be optimized by having a memcpy
- manual_retainthis expression can be written more simply using `.retain()`
- manual_str_repeatmanual implementation of `str::repeat` using iterators
- manual_try_foldusage of `Iterator::fold` on a type that implements `Try`
- map_entryusage of `contains_key` followed by `insert` on a `HashMap`
- missing_const_for_thread_localinitializer for `thread_local` value can be made `const`
- missing_spin_loopbusy-waiting loop should at least have a spin loop hint
- readonly_write_lockthis write lock is used only for reading
- redundant_allocationChecks for usage of redundant allocations anywhere in the code
- redundant_iter_clonedunneeded cloning of iterator items
- regex_creation_in_loopsChecks for regex compilation inside a loop with a literal
- replace_boxcreating a new box with default content
- result_large_errthe `Err`-variant returned from this function is very large
- sliced_string_as_bytescalling `as_bytes` after slicing a string
- slow_vector_initializationChecks slow zero-filled vector initialization
- to_string_in_format_argsChecks for ToString::to_string applied to a type that implements Display in a macro that does formatting
- unbuffered_bytescalling .bytes() is very inefficient when data is not in memory
- unnecessary_to_ownedunnecessary use of `to_string`
- useless_borrows_in_formattingredundant reference in `println!` argument
- useless_vecuseless use of `vec!`
- vec_init_then_pushcalls to `push` immediately after creation
- waker_clone_wakeChecks for usage of waker.clone().wake()
Pedantic (145)
- assert_is_emptyChecks assertions that only test whether a supported value is empty. The lint handles assert! and debug_assert! calls on strings, slices, arrays, and Vec
- assigning_clonesassigning the result of `Clone::clone()` may be inefficient
- bool_to_int_with_ifInstead of using an if statement to convert a bool to an int, this lint suggests using a from() function or an as coercion
- borrow_as_ptrborrow as raw pointer
- case_sensitive_file_extension_comparisonscase-sensitive file extension comparison
- cast_losslesscasts from `u8` to `u64` can be expressed infallibly using `From`
- cast_possible_truncationcasting `u64` to `u8` may truncate the value
- cast_possible_wrapcasting `u32` to `i32` may wrap around the value
- cast_precision_losscasting `u64` to `f64` may cause a loss of precision (`u64` is 64 bits wide, but `f64`'s mantissa is only 52 bits wide)
- cast_ptr_alignmentcasting from `*const u8` to a more-strictly-aligned pointer (`*const u16`) (1 < 2 bytes)
- cast_sign_losscasting `i8` to `u64` may lose the sign of the value
- checked_conversionsChecks for explicit bounds checking when casting
- cloned_instead_of_copiedused `cloned` where `copied` could be used instead
- collapsible_else_ifChecks for collapsible else { if
- comparison_chainChecks comparison chains written with if that can be rewritten with match and cmp
- copy_iteratorChecks for types that implement Copy as well as Iterator
- decimal_bitwise_operandsusing decimal literal for bitwise operation
- default_trait_accesscalling `String::default()` is more clear than this expression
- doc_broken_linkpossible broken doc link: broken across multiple lines
- doc_comment_double_space_linebreaksDetects doc comments that use double spaces as hard line break, instead of backslash (\)
- doc_link_with_quotespossible intra-doc link using quotes instead of backticks
- doc_markdownitem in documentation is missing backticks
- duration_suboptimal_unitsconstructing a `Duration` using a smaller unit when a larger unit would be more readable
- elidable_lifetime_namesChecks for lifetime annotations which can be replaced with anonymous lifetimes ('_)
- enum_glob_useChecks for use Enum::*
- expl_impl_clone_on_copyChecks for explicit Clone implementations for Copy types
- explicit_deref_methodsexplicit `deref` method call
- explicit_into_iter_loopChecks for loops on y.into_iter() where y will do, and suggests the latter
- explicit_iter_loopChecks for loops on x.iter() where &x will do, and suggests the latter
- filter_map_nextcalled `filter_map(..).next()` on an `Iterator`
- flat_map_optionused `flat_map` where `filter_map` could be used instead
- float_cmpstrict comparison of `f32` or `f64`
- fn_params_excessive_boolsChecks for excessive use of bools in function declarations
- format_collectuse of `format!` to build up a string from an iterator
- format_push_string`format!(..)` appended to existing `String`
- if_not_elseChecks for usage of ! or != in an if condition with an else branch
- ignore_without_reasonChecks for ignored tests without messages
- ignored_unit_patternsmatching over `()` is more explicit
- implicit_cloneimplicitly cloning a `Vec` by calling `to_vec` on its dereferenced type
- implicit_hasherChecks for public impl or fn missing generalization over different hashers and implicitly defaulting to the default hashing algorithm (SipHash)
- inconsistent_struct_constructorstruct constructor field order is inconsistent with struct definition field order
- index_refutable_slicethis binding can be a slice pattern to avoid indexing
- inefficient_to_stringChecks for usage of .to_string() on an &&T where T implements ToString directly (like &&str or &&String)
- inline_alwaysChecks for items annotated with #[inline(always)], unless the annotated function is empty or simply panics
- into_iter_without_iterThis is the opposite of the iter_without_into_iter lint. It looks for IntoIterator for (&|&mut) Type implementations without an inherent iter or iter_mut method on the type or on any of the types in its Deref chain
- invalid_upcast_comparisonsbecause of the numeric bounds on `x` prior to casting, this expression is always false
- ip_constanthand-coded well-known IP address
- items_after_statementsadding items after statements is confusing, since items exist from the start of the scope
- iter_filter_is_ok`filter` for `is_ok` on iterator over `Result`s
- iter_filter_is_some`filter` for `is_some` on iterator over `Option`
- iter_not_returning_iteratorthis method is named `iter` but its return type does not implement `Iterator`
- iter_without_into_iterLooks for iter and iter_mut methods without an associated IntoIterator for (&|&mut) Type implementation
- large_digit_groupsdigit groups should be smaller
- large_futureslarge future with a size of 16385 bytes
- large_stack_arraysallocating a local array larger than 16384 bytes
- large_types_passed_by_valuethis argument (2048 byte) is passed by value, but might be more efficient if passed by reference (limit: 256 byte)
- linkedlistChecks for usage of any LinkedList, suggesting to use a Vec or a VecDeque (formerly called RingBuf)
- macro_use_importsChecks for #[macro_use] use
- manual_assertonly a `panic!` in `if`-then statement
- manual_assert_eqused `assert!` with an equality comparison
- manual_bit_widthmanual implementation of `bit_width`
- manual_ilog2manually reimplementing `ilog2`
- manual_instant_elapsedmanual implementation of `Instant::elapsed`
- manual_is_power_of_twomanually reimplementing `is_power_of_two`
- manual_is_variant_andChecks for usage of option.map(f).unwrap_or_default() and result.map(f).unwrap_or_default() where f is a function or closure that returns the bool type. Also checks for equality comparisons like option.map(f) == Some(true) and result.map(f) == Ok(true), as well as result.ok().is_some_and(f)
- manual_let_elseWarn of cases where let...else could be used
- manual_midpointChecks for manual implementation of midpoint
- manual_string_newempty String is being created manually
- many_single_char_names7 bindings with single-character names in scope
- map_unwrap_orChecks for usage of option.map(_).unwrap_or(_) or option.map(_).unwrap_or_else(_) or result.map(_).unwrap_or_else(_)
- match_boolChecks for matches where match expression is a bool
- match_same_armsChecks for match with identical arm bodies. Note: Does not lint on wildcards if the non_exhaustive_omitted_patterns_lint feature is enabled and disallowed
- match_wild_err_arm`Err(_)` matches all errors
- match_wildcard_for_single_variantsChecks for wildcard enum matches for a single variant
- maybe_infinite_iterChecks for iteration that may be infinite
- mismatching_type_param_order`Foo` has a similarly named generic type parameter `B` in its declaration, but in a different order
- missing_errors_docChecks the doc comments of publicly visible functions that return a Result type and warns if there is no # Errors section
- missing_fields_in_debugmanual `Debug` impl does not include all fields
- missing_panics_docChecks the doc comments of publicly visible functions that may panic and warns if there is no # Panics section
- must_use_candidateChecks for public functions that have no #[must_use] attribute, but return something not already marked must-use, have no mutable arg and mutate no statics
- mut_mutmultiple successive mutable borrows
- naive_bytecountChecks for naive byte counts
- needless_bitwise_booluse of bitwise operator instead of lazy operator between booleans
- needless_continueThe lint checks for if-statements appearing in loops that contain a continue statement in either their main blocks or their else-blocks, when omitting the else-block possibly with some rearrangement of code can make the code easier to understand. The lint also checks if the last statement in the loop is a continue
- needless_for_eachneedless use of `for_each`
- needless_pass_by_valuethis argument is passed by value, but not consumed in the function body
- needless_raw_string_hashesunnecessary hashes around raw string literal
- no_effect_underscore_bindingbinding to `_` prefixed variable with no side-effect
- no_mangle_with_rust_abi`#[no_mangle]` set on a function with the default (`Rust`) ABI
- non_std_lazy_staticsLints when once_cell::sync::Lazy or lazy_static! are used to define a static variable, and suggests replacing such cases with std::sync::LazyLock instead. Note: This lint will not trigger in crate with no_std context, or with MSRV < 1.80.0
- nonminimal_boolChecks for boolean expressions that can be written more concisely
- option_as_ref_clonedcloning an `Option<_>` using `.as_ref().cloned()`
- option_optionuse of `Option<Option<T>>`
- overly_complex_bool_exprChecks for boolean expressions that contain terminals that can be eliminated
- ptr_as_ptr`as` casting between raw pointers without changing their constness
- ptr_cast_constness`as` casting between raw pointers while changing only its constness
- ptr_offset_by_literaluse of `offset` with a literal
- pub_underscore_fieldsChecks whether any field of the struct is prefixed with an _ (underscore) and also marked pub (public)
- range_minus_oneChecks for inclusive ranges where 1 is subtracted from the upper bound, e.g., x..=(y-1)
- range_plus_oneChecks for exclusive ranges where 1 is added to the upper bound, e.g., x..(y+1)
- redundant_closure_for_method_callsredundant closure
- redundant_elseredundant else block
- ref_as_ptrreference as raw pointer
- ref_binding_to_referenceChecks for ref bindings which create a reference to a reference
- ref_optionWarns when a function signature uses &Option<T> instead of Option<&T>
- ref_option_refsince `&` implements the `Copy` trait, `&Option<&T>` can be simplified to `Option<&T>`
- return_self_not_must_usemissing `#[must_use]` attribute on a method returning `Self`
- same_functions_in_if_conditionChecks for consecutive ifs with the same function call
- same_length_and_capacityChecks for usages of Vec::from_raw_parts and String::from_raw_parts where the same expression is used for the length and the capacity
- self_only_used_in_recursion`self` is only used in recursion
- semicolon_if_nothing_returnedconsider adding a `;` to the last statement for consistent formatting
- should_panic_without_expectChecks for #[should_panic] attributes without specifying the expected panic message
- similar_namesbinding's name is too similar to existing binding
- single_char_patternChecks for string methods that receive a single-character str as an argument, e.g., _.split("x")
- single_match_elseChecks for matches with two arms where an if let else will usually suffice
- stable_sort_primitiveused `sort` on primitive type `i32`
- str_split_at_newlineChecks for usages of str.trim().split("\n") and str.trim().split("\r\n")
- string_add_assignyou assigned the result of adding something to this string. Consider using `String::push_str()` instead
- struct_excessive_boolsChecks for excessive use of bools in structs
- struct_field_namesfield name starts with the struct's name
- too_many_linesChecks for functions with a large amount of lines
- transmute_ptr_to_ptrtransmute from a pointer to a pointer
- trivially_copy_pass_by_refthis argument (4 byte) is passed by reference, but would be more efficient if passed by value (limit: 8 byte)
- unchecked_time_subtractionLints subtraction between an Instant and a Duration, or between two Duration values
- unicode_not_nfcChecks for string literals that contain Unicode in a form that is not equal to its NFC-recomposition
- uninlined_format_argsDetect when a variable is not inlined in a format string, and suggests to inline it
- unnecessary_box_returnsboxed return of the sized type `std::string::String`
- unnecessary_debug_formattingChecks for Debug formatting ({:?}) applied to an OsStr or Path. This includes: Format specifiers on format_args!() (width, precision have no effect) Format width too small for the format trait (e.g
- unnecessary_joincalled `.collect::<Vec<String>>().join("")` on an iterator
- unnecessary_literal_boundDetects functions that are written to return &str that could return &'static str but instead return a &'a str
- unnecessary_semicolonChecks for the presence of a semicolon at the end of a match or if statement evaluating to ()
- unnecessary_trailing_commaunnecessary trailing comma
- unnecessary_wrapsthis function's return value is unnecessarily wrapped by `Option`
- unnested_or_patternsunnested or-patterns
- unreadable_literallong literal lacking separators
- unsafe_derive_deserializeChecks for deriving serde::Deserialize on a type that has methods using unsafe
- unused_asyncunused `async` for function with no await statements
- unused_async_trait_implunused `async` for async trait impl function with no `.await` statements
- unused_selfunused `self` argument
- used_underscore_bindingused underscore-prefixed binding
- used_underscore_itemsused underscore-prefixed item
- verbose_bit_maskChecks for bit masks that can be replaced by a call to trailing_zeros
- wildcard_importsChecks for wildcard imports use _::*
- with_capacity_zerocalling `with_capacity(0)` is equivalent to `new()`
- zero_sized_map_valuesChecks for maps with zero-sized value types anywhere in the code
Restriction (135)
- absolute_pathsconsider bringing this path into scope with the `use` keyword
- alloc_instead_of_coreFinds items imported through alloc when available through core
- allow_attributes#[allow] attribute found
- allow_attributes_without_reason`allow` attribute without specifying a reason
- arbitrary_source_item_orderingincorrect ordering of items (must be alphabetically ordered)
- arithmetic_side_effectsarithmetic operation that can potentially result in unexpected side-effects
- as_conversionsChecks for usage of as conversions. Note that this lint is specialized in linting every single use of as regardless of whether good alternatives exist or not
- as_pointer_underscoreusing inferred pointer cast
- as_underscoreusing `as _` conversion
- assertions_on_result_statesChecks for assert!(r.is_ok()) or assert!(r.is_err()) calls
- big_endian_bytesuse of `to_be_bytes`
- cfg_not_testcode is excluded from test builds
- clone_on_ref_ptrChecks for usage of .clone() on a ref-counted pointer, (Rc, Arc, rc::Weak, or sync::Weak), and suggests calling Clone via unified function syntax instead (e.g., Rc::clone(foo))
- cognitive_complexityWe used to think it measured how hard a method is to understand
- create_dircalling `std::fs::create_dir` where there may be a better way
- dbg_macroChecks for usage of the dbg! macro
- decimal_literal_representationWarns if there is a better representation for a numeric literal
- default_numeric_fallbackdefault numeric fallback might occur
- default_union_representationthis union has the default representation
- definition_in_module_rootChecks for definitions (structs, functions, traits, etc.) in mod.rs files
- deref_by_slicingslicing when dereferencing would work
- disallowed_script_identsidentifier `счётчик` has a Unicode script that is not allowed by configuration: Cyrillic
- doc_include_without_cfgChecks if included files in doc comments are included only for cfg(doc)
- doc_paragraphs_missing_punctuationChecks for doc comments whose paragraphs do not end with a period or another punctuation mark. Various Markdowns constructs are taken into account to avoid false positives
- else_if_without_else`if` expression with an `else if`, but without a final `else`
- empty_dropempty drop implementation
- empty_enum_variants_with_bracketsenum variant has empty brackets
- empty_structs_with_bracketsfound empty brackets on struct declaration
- error_impl_errorChecks for types named Error that implement Error
- exhaustive_enumsWarns on any exported enums that are not tagged #[non_exhaustive]
- exhaustive_structsWarns on any exported structs that are not tagged #[non_exhaustive]
- exitDetects calls to the exit() function that are not in the main function
- expect_usedChecks for .expect() or .expect_err() calls on Results and .expect() call on Options
- field_scoped_visibility_modifiersscoped visibility modifier on a field
- filetype_is_fileChecks for FileType::is_file()
- float_arithmeticChecks for float arithmetic
- float_cmp_conststrict comparison of `f32` or `f64` constant
- fn_to_numeric_cast_anycasting function pointer `fn1` to `usize`
- get_unwrapcalled `.get().unwrap()` on a Vec
- host_endian_bytesuse of `to_ne_bytes`
- if_then_some_else_noneChecks for if-else that could be written using either bool::then or bool::then_some
- impl_trait_in_paramsLints when impl Trait is being used in a function’s parameters
- implicit_returnmissing `return` statement
- indexing_slicingindexing may panic
- infinite_loopinfinite loop detected
- inline_asm_x86_att_syntaxChecks for usage of AT&T x86 assembly syntax
- inline_asm_x86_intel_syntaxChecks for usage of Intel x86 assembly syntax
- inline_modulesinline module found
- inline_trait_boundsinline trait bounds used
- integer_divisioninteger division
- integer_division_remainder_useduse of `/` has been disallowed in this context
- iter_over_hash_typeiteration over unordered hash-based type
- large_include_fileChecks for the inclusion of large files via include_bytes!() or include_str!()
- let_underscore_must_usenon-binding `let` on an expression with `#[must_use]` type
- let_underscore_untypednon-binding `let` without a type annotation
- little_endian_bytesuse of `to_le_bytes`
- lossy_float_literalliteral cannot be represented as the underlying type without loss of precision
- map_err_ignore`map_err(|_|...` wildcard pattern discards the original error
- map_with_unused_argument_over_rangesmap of a closure that does not depend on its parameter over a range
- mem_forgetChecks for usage of std::mem::forget(t) where t is Drop or has a field that implements Drop
- min_ident_charsChecks for identifiers which consist of a single character (or fewer than the configured threshold). Note: This lint can be very noisy when enabled; it may be desirable to only enable it temporarily
- missing_assert_messageChecks assertions without a custom panic message
- missing_asserts_for_indexingindexing into a slice multiple times without an `assert`
- missing_docs_in_private_itemsWarns if there is missing documentation for any private documentable item
- missing_inline_in_public_itemsmissing `#[inline]` on a publicly callable function
- missing_trait_methodsChecks if a provided method is used implicitly by a trait implementation
- mixed_read_write_in_expressionunsequenced read of `x`
- mod_module_filesChecks that module layout uses only self named module files; bans mod.rs files
- module_name_repetitionsDetects public item names that are prefixed or suffixed by the containing public module’s name
- modulo_arithmeticyou are using modulo operator on constants with different signs: `-17 % 3`
- multiple_inherent_implmultiple implementations of this structure
- multiple_unsafe_ops_per_blockthis `unsafe` block contains 2 unsafe operations, expected only one
- mutex_atomicChecks for usage of Mutex<X> where an atomic will do
- mutex_integerChecks for usage of Mutex<X> where X is an integral type
- needless_raw_stringsunnecessary raw string literal
- non_ascii_literalliteral non-ASCII character detected
- non_zero_suggestionsconsider using `NonZeroU64::from()` for more efficient and type-safe conversion
- panic`panic` should not be present in production code
- panic_in_result_fnused `panic!()` or assertion in a function that returns `Result`
- partial_pub_fieldsmixed usage of pub and non-pub fields
- pathbuf_init_then_pushChecks for calls to push immediately after creating a new PathBuf
- pattern_type_mismatchtype of pattern does not match the expression type
- pointer_formatpointer formatting detected
- precedence_bitsChecks for bit shifting operations combined with bit masking/combining operators and suggest using parentheses
- print_stderruse of `eprintln!`
- print_stdoutuse of `println!`
- pub_useusing `pub use`
- pub_with_shorthandusage of `pub` without `in`
- pub_without_shorthandusage of `pub` with `in`
- question_mark_usedChecks for expressions that use the ? operator and rejects them
- rc_bufferChecks for Rc<T> and Arc<T> when T is a mutable buffer type such as String or Vec
- rc_mutexChecks for Rc<Mutex<T>>
- redundant_test_prefixChecks for test functions (functions annotated with #[test]) that are prefixed with test_ which is redundant
- redundant_type_annotationsredundant type annotation
- ref_patternsusage of ref pattern
- renamed_function_paramsrenamed function parameter of trait impl
- rest_pat_in_fully_bound_structsChecks for unnecessary ‘..’ pattern binding on struct when all fields are explicitly matched
- rest_pattern_accessible_fieldstruct destructuring with rest (`..`)
- return_and_thenuse the `?` operator instead of an `and_then` call
- same_name_methodmethod's name is the same as an existing method in a trait
- self_named_module_filesChecks that module layout uses only mod.rs files
- semicolon_inside_blockSuggests moving the semicolon after a block to the inside of the block, after its last expression
- semicolon_outside_blockSuggests moving the semicolon from a block’s final expression outside of the block
- separated_literal_suffixinteger type suffix should not be separated by an underscore
- shadow_reuse`x` is shadowed
- shadow_sameChecks for bindings that shadow other bindings already in scope, while just changing reference level or mutability
- shadow_unrelatedChecks for bindings that shadow other bindings already in scope, either without an initialization or with one that does not even use the original value
- single_call_fnthis function is only used once
- single_char_lifetime_namessingle-character lifetime names are likely uninformative
- std_instead_of_allocused import from `std` instead of `alloc`
- std_instead_of_coreused import from `std` instead of `core`
- str_to_string`to_string()` called on a `&str`
- string_addyou added something to a string. Consider using `String::push_str()` instead
- string_lit_chars_anyChecks for <string_lit>.chars().any(|i| i == c)
- string_sliceindexing into a string may panic if the index is within a UTF-8 character
- suspicious_xor_used_as_pow`^` is not the exponentiation operator
- tests_outside_test_moduleTriggers when a testing function (marked with the #[test] attribute) isn’t inside a testing module (marked with #[cfg(test)])
- todo`todo` should not be present in production code
- try_errreturning an `Err(_)` with the `?` operator
- undocumented_unsafe_blocksChecks for unsafe blocks and impls without a // SAFETY: comment explaining why the unsafe operations performed inside the block are safe. Note the comment must appear on the line(s) preceding the unsafe block with nothing appearing in between
- unimplemented`unimplemented` should not be present in production code
- unnecessary_rest_patternunnecessary rest pattern (`..`)
- unnecessary_safety_commentstatement has unnecessary safety comment
- unnecessary_safety_docChecks for the doc comments of publicly visible safe functions and traits and warns if there is a # Safety section
- unnecessary_self_importsimport ending with `::{self}`
- unneeded_field_patternyou matched a field with a wildcard pattern, consider using `..` instead
- unreachableusage of the `unreachable!` macro
- unseparated_literal_suffixinteger type suffix should be separated by an underscore
- unused_result_okChecks for calls to Result::ok() without using the returned Option
- unused_trait_namesimporting trait that is only used anonymously
- unwrap_in_result`expect` used in a function that returns a `Result`
- unwrap_usedChecks for .unwrap() or .unwrap_err() calls on Results and .unwrap() call on Options
- use_debugChecks for usage of Debug formatting
- verbose_file_readsChecks for usage of File::read_to_end and File::read_to_string
- wildcard_enum_match_armChecks for wildcard enum matches using _
Nursery (52)
- as_ptr_cast_mutcasting the result of `as_ptr` to *mut u8
- branches_sharing_codeChecks if the blocks of an if/else, or the arms of a match, contain shared code that can be moved out of the branches
- clear_with_drain`drain` used to clear a `Vec`
- coerce_container_to_anyProtects against unintended coercion of references to container types to &dyn Any when the container type dereferences to a dyn Any which could be directly referenced instead
- collection_is_never_readChecks for collections that are never queried
- debug_assert_with_mut_callChecks for function/method calls with a mutable parameter in debug_assert!, debug_assert_eq! and debug_assert_ne! macros
- derive_partial_eq_without_eqChecks for types that derive PartialEq and could implement Eq
- doc_link_codecode link adjacent to code text
- empty_enumsChecks for enums with no variants, which therefore are uninhabited types (cannot be instantiated). As of this writing, the never_type is still a nightly-only experimental API. Therefore, this lint is only triggered if #![feature(never_type)] is enabled
- equatable_if_letChecks for pattern matchings that can be expressed using equality
- fallible_impl_fromconsider implementing `TryFrom` instead
- future_not_sendfuture cannot be sent between threads safely
- imprecise_flopscube-root of a number can be computed more accurately
- iter_on_empty_collectionsChecks for calls to iter, iter_mut or into_iter on empty collections
- iter_on_single_items`iter` call on a collection with only one item
- iter_with_drainChecks for usage of .drain(..) on Vec and VecDeque for iteration
- large_stack_framesChecks for functions that use a lot of stack space. This often happens when constructing a large type, such as an array with a lot of elements, or constructing many smaller-but-still-large structs, or copying around a lot of large types. This lint is a more general version of large_stack_arrays that is intended to look at functions as a whole instead of only individual array expressions inside of a function
- literal_string_with_formatting_argsthis looks like a formatting argument but it is not part of a formatting macro
- missing_const_for_fnthis could be a `const fn`
- needless_collectChecks for functions collecting an iterator when collect is not needed
- needless_pass_by_ref_mutthis parameter is a mutable reference but is not used mutably
- needless_type_castChecks for bindings (constants, statics, or let bindings) that are defined with one numeric type but are consistently cast to a different type in all usages
- non_send_fields_in_send_tyThis lint warns about a Send implementation for a type that contains fields that are not safe to be sent across threads. It tries to detect fields that can cause a soundness issue when sent to another thread (e.g., Rc) while allowing !Send fields that are expected to exist in a Send type, such as raw pointers
- option_if_let_elseLints usage of if let Some(v) =
- or_fun_callChecks for calls to .or(foo(..)), .unwrap_or(foo(..)), .or_insert(foo(..)) etc., and suggests to use .or_else(|| foo(..)), .unwrap_or_else(|| foo(..)), .unwrap_or_default() or .or_default() etc
- path_buf_push_overwritecalling `push` with '/' or '\' (file system root) will overwrite the previous path definition
- read_zero_byte_vecreading zero byte data to `Vec`
- redundant_cloneChecks for a redundant clone() (and its relatives) which clones an owned value that is going to be dropped without further use
- redundant_pub_cratepub(crate) function inside private module
- search_is_somecalled `is_some()` after searching an `Iterator` with `find`
- set_contains_or_insertusage of `HashSet::insert` after `HashSet::contains`
- significant_drop_in_scrutineeChecks for temporaries returned from function calls in a match scrutinee that have the clippy::has_significant_drop attribute
- significant_drop_tighteningSearches for elements marked with #[clippy::has_significant_drop] that could be early dropped but are in fact dropped at the end of their scopes
- single_option_map`fn` that only maps over argument
- string_lit_as_bytesChecks for the as_bytes method called on string literals that contain only ASCII characters
- suboptimal_flopsexponent for bases 2 and e can be computed more accurately
- suspicious_operation_groupingsthis sequence of operators looks suspiciously like a bug
- too_long_first_doc_paragraphChecks if the first paragraph in the documentation of items listed in the module page is too long
- trailing_empty_arraytrailing zero-sized array in a struct which is not marked with a `repr` attribute
- trait_duplication_in_boundsthis trait bound is already specified in the where clause
- transmute_undefined_reprtransmute from `main::Foo<u32>` to `main::Foo<i32>`, both of which have an undefined layout
- trivial_regexChecks for trivial regex creation (with Regex::new, RegexBuilder::new, or RegexSet::new)
- tuple_array_conversionsit looks like you're trying to convert a tuple to an array
- type_repetition_in_boundstype `T` has already been used as a bound predicate
- uninhabited_referencesdereferencing a reference to an uninhabited type would be undefined behavior
- unnecessary_struct_initializationunnecessary struct building
- unused_peekable`peek` never called on `Peekable` iterator
- unused_roundingused the `ceil` method with a whole number float
- use_selfunnecessary structure name repetition
- useless_let_if_seqChecks for variable declarations immediately followed by a conditional affectation
- volatile_compositestype `main::MyDevice` is not volatile-compatible
- while_floatwhile condition comparing floats
Cargo (5)
- cargo_common_metadataChecks to see if all common metadata is defined in Cargo.toml
- multiple_crate_versionsChecks to see if multiple versions of a crate are being used
- negative_feature_namesChecks for negative feature names with prefix no- or not-
- redundant_feature_namesChecks for feature names with prefix use-, with- or suffix -support
- wildcard_dependenciesChecks for wildcard dependencies in the Cargo.toml
Deprecated (17)
- assign_opsNothing
- extend_from_sliceNothing
- from_iter_instead_of_collectNothing
- match_on_vec_itemsNothing
- misaligned_transmuteNothing
- option_map_or_err_okNothing
- pub_enum_variant_namesNothing
- range_step_by_zeroNothing
- regex_macroNothing
- replace_constsNothing
- should_assert_eqNothing
- string_to_stringNothing
- unsafe_vector_initializationNothing
- unstable_as_mut_sliceNothing
- unstable_as_sliceNothing
- unused_collectNothing
- wrong_pub_self_conventionNothing
How we built this
We parsed Clippy's stable lint list for Rust 1.99, then ran clippy-driver from the same toolchain on each lint's example and kept the exact warning it printed. Lint docs are from the Rust project (MIT or Apache-2.0).
Up next
Same toolboxRust compiler errors, explained with fixesFor rustc errors like E0382 and E0502.Read it next →Also worth your time
Did this answer your question?