### Inconsistent Struct Constructor Example Source: https://rust-lang.github.io/rust-clippy/stable/index Illustrates the inconsistency in struct field initialization order within constructors, showing an example that works but is less readable and the preferred, consistent order. ```rust struct Foo { x: i32, y: i32, } let x = 1; let y = 2; Foo { y, x }; Use instead: Foo { x, y }; ``` -------------------------------- ### Indexing and Slicing Example Source: https://rust-lang.github.io/rust-clippy/stable/index Demonstrates potentially panicking indexing and slicing operations on vectors and arrays, and shows the 'checked' alternatives using the `.get()` method. ```rust // Vector let x = vec![0, 1, 2, 3]; x[2]; x[100]; &x[2..100]; // Array let y = [0, 1, 2, 3]; let i = 10; // Could be a runtime value let j = 20; &y[i..j]; Use instead: x.get(2); x.get(100); x.get(2..100); let i = 10; let j = 20; y.get(i..j); ``` -------------------------------- ### Rust: Example of `as` conversion with potential lossy truncation Source: https://rust-lang.github.io/rust-clippy/stable/index This example shows a common usage of the `as` keyword for type conversion, specifically casting a `u32` to a `u16`. The lint `as_conversions` flags this because `as` can perform silently lossy conversions. It suggests using `try_into()` for safer, fallible conversions. ```rust let a: u32; ... f(a as u16); ``` -------------------------------- ### Rust: Example of a doctest with a main function Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet demonstrates a doctest in Rust that includes a `main()` function. It's noted that the main function itself is not strictly necessary within the doctest context, but the example showcases the structure. ```rust /// An example of a doctest with a `main()` function /// /// # Examples /// /// ``` /// fn main() { /// // this needs not be in an `fn` /// } /// ``` fn needless_main() { unimplemented!(); } ``` -------------------------------- ### Rust Module and Struct Definition Example Source: https://rust-lang.github.io/rust-clippy/stable/index This example illustrates defining a module named 'cake' containing a struct 'BlackForestCake'. It's provided as context for a refactoring example that aims to simplify naming conventions within modules. ```rust mod cake { struct BlackForestCake; } ``` -------------------------------- ### File Creation and Permissions in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index Demonstrates creating a file named 'foo.txt', getting its metadata, and modifying its permissions to be non-read-only. This is useful for understanding file manipulation in Rust. ```rust use std::fs::File; let f = File::create("foo.txt").unwrap(); let metadata = f.metadata().unwrap(); let mut permissions = metadata.permissions(); permissions.set_readonly(false); ``` -------------------------------- ### Ordered Trait Example (Rust) Source: https://rust-lang.github.io/rust-clippy/stable/index This Rust code snippet shows the same trait as the previous example, but with its associated items ordered alphabetically. This version would comply with the module-item-order lint's requirements for ordered traits. ```rust trait TraitOrdered { const A: bool; const B: bool; const C: bool; type SomeType; fn a(); fn b(); fn c(); } ``` -------------------------------- ### Example of Module Structure in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet demonstrates a basic module structure in Rust. It shows how to define a module and then re-export its contents using a glob import. This is relevant for understanding how paths are created and how Clippy might analyze them. ```rust pub mod foo { mod iteration { pub struct FooIter {} } pub use iteration::*; } ``` -------------------------------- ### Example of AddAssign implementation in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet demonstrates a basic implementation of the `AddAssign` trait for a type `Foo`. It shows how to define the `add_assign` method, which modifies the left-hand side operand in place using the addition assignment operator (`+=`). In this specific example, the implementation incorrectly uses subtraction instead of addition. ```rust impl AddAssign for Foo { fn add_assign(&mut self, other: Foo) { *self = *self - other; } } ``` -------------------------------- ### Inconsistent Digit Grouping Example Source: https://rust-lang.github.io/rust-clippy/stable/index Demonstrates how integral and floating-point constants can be grouped inconsistently with underscores, and shows the preferred, consistent grouping. ```rust 618_64_9189_73_511 Use instead: 61_864_918_973_511 ``` -------------------------------- ### Rust: Simplify default value unwrapping with unwrap_or_default Source: https://rust-lang.github.io/rust-clippy/stable/index This example shows how to simplify code by replacing usages of `unwrap_or` with `Default::default()` and `or_insert_with` with `String::new()` with their more concise counterparts, `unwrap_or_default` and `or_default` respectively. This improves readability. ```rust x.unwrap_or_default(); map.entry(42).or_default(); ``` -------------------------------- ### Use `is_some_and` and `is_ok_and` in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This example demonstrates replacing verbose `option.map(...).unwrap_or_default()` and `result.map(...).unwrap_or_default()` patterns with the more concise `is_some_and` and `is_ok_and` methods, respectively. This improves code readability. ```Rust option.map(|a| a > 10).unwrap_or_default(); result.map(|a| a > 10).unwrap_or_default(); option.map(|a| a > 10) == Some(true); result.map(|a| a > 10) == Ok(true); option.map(|a| a > 10) != Some(true); result.map(|a| a > 10) != Ok(true); ``` ```Rust option.is_some_and(|a| a > 10); result.is_ok_and(|a| a > 10); option.is_some_and(|a| a > 10); result.is_ok_and(|a| a > 10); option.is_none_or(|a| a > 10); !result.is_ok_and(|a| a > 10); ``` -------------------------------- ### Rust: Safer alternative to `as` conversion using `try_into` Source: https://rust-lang.github.io/rust-clippy/stable/index This example demonstrates the recommended, safer alternative to potentially lossy `as` conversions. Using `try_into()` allows for explicit error handling (e.g., with `?` or `.expect()`) if the conversion fails, preventing unexpected data loss or panics. ```rust f(a.try_into()?); // or f(a.try_into().expect("Unexpected u16 overflow in f")); ``` -------------------------------- ### Rust: Struct and Implementation Example Source: https://rust-lang.github.io/rust-clippy/stable/index Demonstrates a basic Rust struct `Foo` with a `new` associated function. It shows two equivalent implementations: one using `Foo` and `Foo {}` and another using `Self` and `Self {}` for the return type and instantiation. ```rust struct Foo; impl Foo { fn new() -> Foo { Foo {} } } ``` ```rust struct Foo; impl Foo { fn new() -> Self { Self {} } } ``` -------------------------------- ### Configure Module Item Order Groupings (TOML) Source: https://rust-lang.github.io/rust-clippy/stable/index This example demonstrates how to configure custom groupings for module item order using TOML syntax. It specifies that 'modules' and 'use' statements should appear first, followed by all other items. ```toml module-item-order-groupings = [ [ "modules", [ "extern_crate", "mod", "foreign_mod" ], ], [ "use", [ "use", ], ], [ "everything_else", [ "macro", "global_asm", "static", "const", "ty_alias", "enum", "struct", "union", "trait", "trait_alias", "impl", "fn", ], ], ] ``` -------------------------------- ### Rust Loop Example Source: https://rust-lang.github.io/rust-clippy/stable/index A basic Rust loop structure that includes a placeholder for operations and a break condition. ```rust loop { ..; break; } ``` -------------------------------- ### Example Usage of Disallowed Methods Source: https://rust-lang.github.io/rust-clippy/stable/index Demonstrates the usage of methods that might be disallowed by `clippy.toml` configuration, such as `Vec::leak`, `Instant::now`, and `Box::new`. It also shows an alternative approach using `Vec::new` and `Vec::push`. ```rust let xs = vec![1, 2, 3, 4]; xs.leak(); // Vec::leak is disallowed in the config. // The diagnostic contains the message "no leaking memory". let _now = Instant::now(); // Instant::now is disallowed in the config. let _box = Box::new(3); // Box::new is disallowed in the config. ``` ```rust let mut xs = Vec::new(); // Vec::new is _not_ disallowed in the config. xs.push(123); // Vec::push is _not_ disallowed in the config. ``` -------------------------------- ### Use strip_prefix/suffix over starts/ends_with - Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet recommends using `strip_prefix` and `strip_suffix` instead of `starts_with` and slicing. The `strip_prefix/suffix` methods are safer, potentially more performant, and can improve code readability. The example shows how to replace code using `starts_with` and slicing with `strip_prefix`. ```rust let s = "hello, world!"; if s.starts_with("hello, ") { assert_eq!(s["hello, ".len()..].to_uppercase(), "WORLD!"); } ``` ```rust let s = "hello, world!"; if let Some(end) = s.strip_prefix("hello, ") { assert_eq!(end.to_uppercase(), "WORLD!"); } ``` -------------------------------- ### Slice Binding in Patterns Example Source: https://rust-lang.github.io/rust-clippy/stable/index Compares accessing slice elements by index, which can panic, with using refutable slice patterns in `if let` for safer and more readable access. ```rust let slice: Option<&[u32]> = Some(&[1, 2, 3]); if let Some(slice) = slice { println!("{}", slice[0]); } Use instead: let slice: Option<&[u32]> = Some(&[1, 2, 3]); if let Some(&[first, ..]) = slice { println!("{}", first); } ``` -------------------------------- ### Use `format!` for String Formatting Arguments in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index Demonstrates a case where a string literal with formatting arguments is used outside of a macro like `format!`. The example shows how to correctly use `format!` to achieve the desired string output. ```rust let x: Option = None; let y = "hello"; x.expect("{y:?}"); ``` ```rust let x: Option = None; let y = "hello"; x.expect(&format!("{y:?}")); ``` -------------------------------- ### Rust: Use const initializer in thread_local! Source: https://rust-lang.github.io/rust-clippy/stable/index Illustrates how to improve the efficiency of `thread_local!` macros in Rust by using a `const` initializer. The example contrasts a standard initialization with a `const` block, which can lead to more efficient thread-local storage. ```rust thread_local! { static BUF: String = String::new(); } ``` ```rust thread_local! { static BUF: String = const { String::new() }; } ``` -------------------------------- ### Use Descriptive Names for Lifetimes in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index Illustrates the use of single-character lifetime names, which can be unclear, and provides an improved example using a more descriptive name ('src') to enhance code readability and maintainability. ```rust struct DiagnosticCtx<'a> { source: &'a str, } ``` ```rust struct DiagnosticCtx<'src> { source: &'src str, } ``` -------------------------------- ### Rust: Suggest const fn for functions Source: https://rust-lang.github.io/rust-clippy/stable/index Shows how to convert a regular Rust function to a `const fn` to enable its use in const contexts. The example highlights a constructor function that can be made const, improving performance and allowing const evaluation. ```rust fn a() -> i32 { 0 } fn b() -> i32 { a() } ``` ```rust fn new() -> Self { Self { random_number: 42 } } ``` ```rust const fn new() -> Self { Self { random_number: 42 } } ``` -------------------------------- ### Rust: Optimize bounds checks with assert Source: https://rust-lang.github.io/rust-clippy/stable/index Demonstrates how to optimize Rust code by reducing redundant bounds checks using an assert statement. The first example shows code with multiple bounds checks, while the second illustrates the optimized version with a single assert, leading to no bounds checks. ```rust fn sum(v: &[u8]) -> u8 { // 4 bounds checks v[0] + v[1] + v[2] + v[3] } ``` ```rust fn sum(v: &[u8]) -> u8 { assert!(v.len() > 3); // no bounds checks v[0] + v[1] + v[2] + v[3] } ``` -------------------------------- ### Implementing All Trait Methods in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet explains the `missing_trait_methods` lint in Rust, which checks if all required and provided methods of a trait are implemented. It shows an example of an incomplete trait implementation and how to correctly implement all methods. ```rust trait Trait { fn required(); fn provided() {} } #[warn(clippy::missing_trait_methods)] impl Trait for Type { fn required() { /* ... */ } } ``` ```rust trait Trait { fn required(); fn provided() {} } #[warn(clippy::missing_trait_methods)] impl Trait for Type { fn required() { /* ... */ } fn provided() { /* ... */ } } ``` -------------------------------- ### Prefer `starts_with` over `chars().next()` for String Prefix Checks Source: https://rust-lang.github.io/rust-clippy/stable/index This lint flags the use of `str::chars().next()` to check if a string starts with a particular character. It recommends using the more idiomatic and readable `str::starts_with()` method for this purpose. ```rust let name = "example"; if name.chars().next() == Some('_') {}; if name.starts_with('_') {}; ``` -------------------------------- ### Configuring Excessive Nesting Threshold in Clippy Source: https://rust-lang.github.io/rust-clippy/stable/index This example shows how to configure the `excessive-nesting-threshold` in `clippy.toml` to warn about deeply nested code blocks. This helps in maintaining code readability by limiting nesting depth. ```toml excessive-nesting-threshold = 3 ``` -------------------------------- ### Documenting Panics in Rust Functions Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet demonstrates how to document potential panics in Rust functions using the `# Panics` section in doc comments. It shows an example of a function that panics when dividing by zero and how to use `#[expect]` or `#[allow]` to manage or ignore panics. ```rust /// # Panics /// /// Will panic if y is 0 pub fn divide_by(x: i32, y: i32) -> i32 { if y == 0 { panic!("Cannot divide by 0") } else { x / y } } ``` ```rust pub fn will_not_panic(x: usize) { #[expect(clippy::missing_panics_doc, reason = "infallible")] let y = NonZeroUsize::new(1).unwrap(); // If any panics are added in the future the lint will still catch them } ``` -------------------------------- ### Configure Lint Priorities in `Cargo.toml` Source: https://rust-lang.github.io/rust-clippy/stable/index Illustrates how to specify lint priorities in `Cargo.toml` to ensure correct lint override behavior. The example shows setting a priority for the `pedantic` lint to override group priorities. ```toml [lints.clippy] pedantic = "warn" similar_names = "allow" ``` ```toml [lints.clippy] pedantic = { level = "warn", priority = -1 } similar_names = "allow" ``` -------------------------------- ### Optimizing Spin Loops in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet addresses the issue of empty spin loops in Rust, which can waste CPU cycles. It provides an example of an inefficient spin loop and suggests using `std::hint::spin_loop()` or other methods to make it more efficient and conserve energy. ```rust use core::sync::atomic::{AtomicBool, Ordering}; let b = AtomicBool::new(true); // give a ref to `b` to another thread,wait for it to become false while b.load(Ordering::Acquire) {}; ``` ```rust while b.load(Ordering::Acquire) { std::hint::spin_loop() } ``` -------------------------------- ### Example of Modulo Arithmetic with Negative Numbers in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This Rust code snippet demonstrates the use of the modulo operator (%) with a negative number. It highlights potential differences in results compared to other languages when dealing with negative operands, as explained by the `modulo_arithmetic` lint. ```rust let x = -17 % 3; ``` -------------------------------- ### Check for incompatible bit masks in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This Rust example shows a bit mask comparison that can lead to a constant true or false result, indicating a potential logic error or misleading code. ```rust if (x & 1 == 2) { } ``` -------------------------------- ### Safe Program Termination in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet provides examples of safe program termination in Rust. It contrasts the immediate termination of `std::process::exit()` with safer alternatives like `panic!` (for error reporting) or returning a `Result` from `main`. ```rust fn main() { std::process::exit(0); } fn other_function() { std::process::exit(0); } // To provide a stacktrace and additional information panic!("message"); // or a main method with a return fn main() -> Result<(), i32> { Ok(()) } ``` -------------------------------- ### Rust: Avoid Debug formatting in println! Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet shows an example of using the `Debug` formatting specifier `{:?}` within a `println!` macro. The lint `use_debug` aims to catch these as they are intended for debugging and not user-facing output. ```rust println!("{:?}", foo); ``` -------------------------------- ### Rust: Correct upper case acronyms in struct names Source: https://rust-lang.github.io/rust-clippy/stable/index This example demonstrates correcting naming conventions for struct names that contain acronyms. It shows how to change a fully capitalized acronym to follow CamelCase conventions for better readability and consistency. ```rust struct HttpResponse; ``` -------------------------------- ### Rust: Detecting unused underscore binding Source: https://rust-lang.github.io/rust-clippy/stable/index This lint checks for the use of bindings that start with a single underscore, which conventionally signifies an unused variable. Using such a binding breaks this convention, making the code less intuitive. The example shows `_x` being used when it should have been renamed to `x`. ```rust let _x = 0; let y = _x + 1; // Here we are using `_x`, even though it has a leading // underscore. We should rename `_x` to `x` ``` -------------------------------- ### Replace `LinkedList` with `Vec` or `VecDeque` in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index Shows an example of `LinkedList` initialization in Rust. The lint suggests using `Vec` or `VecDeque` for better performance due to reduced memory overhead and improved cache locality. ```rust let x: LinkedList = LinkedList::new(); ``` -------------------------------- ### Rust: Detecting unused underscore items Source: https://rust-lang.github.io/rust-clippy/stable/index This lint identifies the use of functions or structs that start with a single underscore, which typically indicates they are not intended for public use or are intentionally unused. The example demonstrates how to refactor `_foo()` and `_FooStruct` into `foo()` and `FooStruct` respectively, while correctly handling unused items. ```rust fn _foo() {} struct _FooStruct {} fn main() { _foo(); let _ = _FooStruct{}; } ``` ```rust fn foo() {} struct FooStruct {} fn main() { foo(); let _ = FooStruct{}; } ``` -------------------------------- ### Ensuring Safety Documentation for Unsafe Rust Functions Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet illustrates the importance of documenting safety preconditions for publicly visible unsafe Rust functions. It shows an example of an undocumented unsafe function and how to add a `# Safety` section to its doc comment to explain its usage. ```rust /// This function should really be documented pub unsafe fn start_apocalypse(u: &mut Universe) { unimplemented!(); } ``` ```rust /// # Safety /// /// This function should not be called before the horsemen are ready. pub unsafe fn start_apocalypse(u: &mut Universe) { unimplemented!(); } ``` -------------------------------- ### Rust: Avoid confusing zero-prefixed literals Source: https://rust-lang.github.io/rust-clippy/stable/index This lint warns if an integral constant literal starts with `0`. In Rust, a leading `0` denotes a decimal constant, unlike in C where it signifies an octal constant. This difference can lead to confusion for developers familiar with C or other languages. The examples demonstrate the differing interpretations in Rust and C. ```rust fn main() { let a = 0123; println!("{}", a); } ``` ```c #include int main() { int a = 0123; printf("%d\n", a); } ``` -------------------------------- ### Handle Path::join with leading separators correctly (Rust) Source: https://rust-lang.github.io/rust-clippy/stable/index This lint warns about using `Path::join` with a path segment that starts with a separator (`\` or `/`). Doing so overwrites the original path, which might be unintentional. The example shows how to either remove the leading separator for standard joining or use `Path::new` if a completely new path is intended. Note that the behavior is platform-dependent. ```rust let path = Path::new("/bin"); let joined_path = path.join("/sh"); assert_eq!(joined_path, PathBuf::from("/sh")); // Use instead; let path = Path::new("/bin"); // If this was unintentional, remove the leading separator let joined_path = path.join("sh"); assert_eq!(joined_path, PathBuf::from("/bin/sh")); // If this was intentional, create a new path instead let new = Path::new("/sh"); assert_eq!(new, PathBuf::from("/sh")); ``` -------------------------------- ### Use `create_dir_all` Instead of `create_dir` (Rust) Source: https://rust-lang.github.io/rust-clippy/stable/index Suggests using `std::fs::create_dir_all` instead of `std::fs::create_dir`. `create_dir` can fail if multiple directories need creation or if the directory already exists, which `create_dir_all` handles. This lint helps prevent mistakes when creating directories. ```rust std::fs::create_dir("foo"); ``` ```rust std::fs::create_dir_all("foo"); ``` -------------------------------- ### Rust: Fix create_dir to use Ok(()) Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet demonstrates a fix for creating a directory in Rust. The original code used `Ok(_)` which is less specific than `Ok(())`. The corrected version uses `Ok(())` to explicitly indicate that the success value is the unit type, improving clarity. ```rust match std::fs::create_dir("tmp-work-dir") { Ok(_) => println!("Working directory created"), Err(s) => eprintln!("Could not create directory: {s}"), } ``` ```rust match std::fs::create_dir("tmp-work-dir") { Ok(()) => println!("Working directory created"), Err(s) => eprintln!("Could not create directory: {s}"), } ``` -------------------------------- ### Replace mem::replace Option with None using take() Source: https://rust-lang.github.io/rust-clippy/stable/index This lint warns about using `std::mem::replace` to replace an `Option` with `None`. The `Option::take()` method is a more idiomatic and efficient way to achieve the same result. The example shows the incorrect and preferred methods. ```rust use std::mem; let mut an_option = Some(0); let replaced = mem::replace(&mut an_option, None); ``` ```rust let mut an_option = Some(0); let taken = an_option.take(); ``` -------------------------------- ### Use split_once instead of splitn(2) - Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet recommends using `split_once` instead of `str::splitn(2, _)` for splitting a string. The `split_once` method is clearer in intent and can be slightly more efficient. The example demonstrates replacing usages of `splitn` with `split_once`. ```rust let s = "key=value=add"; let (key, value) = s.splitn(2, '=').next_tuple()?; let value = s.splitn(2, '=').nth(1)?; let mut parts = s.splitn(2, '='); let key = parts.next()?; let value = parts.next()?; ``` ```rust let s = "key=value=add"; let (key, value) = s.split_once('=')?; let value = s.split_once('=')?.1; let (key, value) = s.split_once('=')?; ``` -------------------------------- ### Example of Modulo Operation by One or Minus One in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This Rust code illustrates taking the remainder of an integer division by 1 or -1 using the modulo operator (%). This is flagged by the `modulo_one` lint due to the predictable and often erroneous results these operations produce. ```rust let a = x % 1; let a = x % -1; ``` -------------------------------- ### Rust: Enforce import renames with clippy.toml Source: https://rust-lang.github.io/rust-clippy/stable/index Demonstrates how to enforce consistent import renaming in Rust projects using Clippy's configuration. The example shows a `clippy.toml` setting to rename `serde_json::Value` to `JsonValue` and the corresponding `use` statement before and after the rename. ```toml enforced-import-renames = [ { path = "serde_json::Value", rename = "JsonValue" }, ] ``` ```rust use serde_json::Value; ``` ```rust use serde_json::Value as JsonValue; ``` -------------------------------- ### Use String Methods Directly Instead of as_bytes() Source: https://rust-lang.github.io/rust-clippy/stable/index This lint identifies instances where `str::as_bytes()` is called before `len()` or `is_empty()`, which is redundant as these methods are directly available on strings and yield the same results. The examples show how to call `len()` and `is_empty()` directly on a string literal. ```rust let len = "some string".as_bytes().len(); let b = "some string".as_bytes().is_empty(); ``` ```rust let len = "some string".len(); let b = "some string".is_empty(); ``` -------------------------------- ### Use `is_multiple_of` in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This example shows the use of the `is_multiple_of` method in Rust. This improves readability compared to the modulo operator in the context of checking for divisibility. ```Rust if a % b == 0 { println!("{a} is divisible by {b}"); } ``` ```Rust if a.is_multiple_of(b) { println!("{a} is divisible by {b}"); } ``` -------------------------------- ### Avoid Empty Loops Source: https://rust-lang.github.io/rust-clippy/stable/index Highlights the issue of empty `loop` expressions, which consume CPU resources without performing any action. The example shows a basic empty loop and implies that alternative constructs like `panic!`, blocking, sleeping, or yielding are preferable. ```rust loop {} ``` -------------------------------- ### Replace mem::replace with Default using take() Source: https://rust-lang.github.io/rust-clippy/stable/index This lint identifies instances where `std::mem::replace` is used to replace a value with its default. The `std::mem::take` function provides a more concise and direct way to achieve this. The example demonstrates the inefficient and preferred patterns. ```rust let mut text = String::from("foo"); let replaced = std::mem::replace(&mut text, String::default()); ``` ```rust let mut text = String::from("foo"); let taken = std::mem::take(&mut text); ``` -------------------------------- ### Rust: Use precise floating-point methods for accuracy Source: https://rust-lang.github.io/rust-clippy/stable/index This lint identifies floating-point expressions that can be replaced with more accurate built-in methods, potentially at the cost of performance. Examples include using `cbrt()` instead of `powf(1.0 / 3.0)`, `ln_1p()` for `ln(1.0 + a)`, and `exp_m1()` for `exp() - 1.0`. ```rust let a = 3f32; let _ = a.cbrt(); let _ = a.ln_1p(); let _ = a.exp_m1(); ``` -------------------------------- ### Use PathBuf::from or join for PathBuf Construction in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index Identifies instances where `PathBuf::new()` is followed by `push()`. This lint suggests using `PathBuf::from()` for new `PathBuf`s or chaining `join()` calls for better readability and potential performance benefits by avoiding implicit clones. It aims to simplify path manipulation code. ```rust let mut path_buf = PathBuf::new(); path_buf.push("foo"); ``` ```rust let path_buf = PathBuf::from("foo"); // or let path_buf = PathBuf::new().join("foo"); ``` -------------------------------- ### Correct Mistyped Literal Suffixes in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This lint warns about mistyped suffix in numeric literals, which is usually a typo. It provides examples of incorrect and corrected literal suffix usage. ```rust `2_32` => `2_i32` `250_8 => `250_u8` ``` -------------------------------- ### Avoid Little-Endian Byte Conversions in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index Provides examples of using `to_le_bytes` for integer types in Rust. The lint discourages this, recommending the use of big-endian or target-specific endianness for consistency. ```rust let _x = 2i32.to_le_bytes(); let _y = 2i64.to_le_bytes(); ``` -------------------------------- ### Rust: Detect arithmetic side effects in `rust_decimal::Decimal` addition Source: https://rust-lang.github.io/rust-clippy/stable/index This example demonstrates how third-party types, like `rust_decimal::Decimal`, can also present unwanted side effects such as overflow when performing arithmetic operations. The lint aims to identify these potential issues. ```rust use rust_decimal::Decimal; let _n = Decimal::MAX + Decimal::MAX; ``` -------------------------------- ### Rust: Simplify lifetime annotations Source: https://rust-lang.github.io/rust-clippy/stable/index Checks for lifetime annotations which can be replaced with anonymous lifetimes (`'_`). This makes the code look less complicated. The example shows replacing an explicit lifetime `'a` with `'_`. ```rust fn f<'a>(x: &'a str) -> Chars<'a> { x.chars() } ``` ```rust fn f(x: &str) -> Chars<'_> { x.chars() } ``` -------------------------------- ### Refactor for Similar Name Detection in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index Shows an example of variable names that are too similar, potentially causing confusion, and implies a refactoring would involve renaming one or both variables to be more distinct. ```rust let checked_exp = something; let checked_expr = something_else; ``` -------------------------------- ### Struct Field Initializer Side Effects Example Source: https://rust-lang.github.io/rust-clippy/stable/index Shows a potential semantic change or borrow check error when reordering struct constructor fields if the initializer expressions have side effects. ```rust struct MyStruct { vector: Vec, length: usize } fn main() { let vector = vec![1,2,3]; MyStruct { length: vector.len(), vector}; } ``` -------------------------------- ### Initialize Vec with capacity using `Vec::with_capacity` Source: https://rust-lang.github.io/rust-clippy/stable/index This lint points out that `Vec::with_capacity` is a more concise way to create a vector with a known initial capacity compared to `vec![]` followed by `reserve()`. ```rust let mut v: Vec = vec![]; v.reserve(10); ``` ```rust let mut v: Vec = Vec::with_capacity(10); ``` -------------------------------- ### Rust: Demonstrate `Send` and `Sync` for `Arc` with `RefCell` Source: https://rust-lang.github.io/rust-clippy/stable/index This example demonstrates the use of `Arc` with `RefCell`. It highlights that `RefCell` is not `Sync`, suggesting alternatives like `Rc` or `RwLock` for thread-safe operations. ```rust fn main() { // This is fine, as `i32` implements `Send` and `Sync`. let a = Arc::new(42); // `RefCell` is `!Sync`, so either the `Arc` should be replaced with an `Rc` // or the `RefCell` replaced with something like a `RwLock` let b = Arc::new(RefCell::new(42)); } ``` -------------------------------- ### Rust: Simplifying boolean comparisons in assert macros Source: https://rust-lang.github.io/rust-clippy/stable/index Demonstrates how to simplify boolean comparisons in `assert_eq!` and `assert_ne!` macros by using direct boolean logic. ```rust assert_eq!("a".is_empty(), false); assert_ne!("a".is_empty(), true); ``` ```rust assert!(!"a".is_empty()); ``` -------------------------------- ### Rust: Remove empty Drop implementations Source: https://rust-lang.github.io/rust-clippy/stable/index Checks for empty `Drop` implementations, which have no effect when dropping an instance of the type and are most likely useless. The example shows removing an empty `impl Drop for S` block. ```rust struct S; impl Drop for S { fn drop(&mut self) {} } ``` ```rust struct S; ``` -------------------------------- ### Rust: Generalize HashMap/HashSet constructors for custom hashers Source: https://rust-lang.github.io/rust-clippy/stable/index This lint checks for public `impl` or `fn` that implicitly default to the standard `SipHash` algorithm for `HashMap` or `HashSet`. The example shows a `Serialize` implementation for `HashMap` and a function `foo` taking a mutable reference to a `HashMap`. The suggested rewrite generalizes these to accept any `BuildHasher` type, allowing for custom hashers. ```rust impl Serialize for HashMap { } pub fn foo(map: &mut HashMap) { } ``` ```rust impl Serialize for HashMap { } pub fn foo(map: &mut HashMap) { } ``` -------------------------------- ### Rust: Remove empty documentation comments Source: https://rust-lang.github.io/rust-clippy/stable/index Detects documentation that is empty. Empty docs clutter code without adding value. The example shows removing a single `///` line before a function. ```rust /// fn returns_true() -> bool { true } ``` ```rust fn returns_true() -> bool { true } ``` -------------------------------- ### Using map instead of and_then/or_else in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This Rust example highlights an anti-pattern where `and_then` or `or_else` are used with closures that simply return `Some` or `Err`. The lint suggests using `map` or `map_err` for conciseness. -------------------------------- ### Use .first() or .front() instead of .get(0) Source: https://rust-lang.github.io/rust-clippy/stable/index This lint checks for the usage of `x.get(0)` to retrieve the first element of a collection. It recommends using the more idiomatic and readable `x.first()` for Vecs and slices, or `x.front()` for VecDeques, which provide the same functionality. ```rust let x = vec![2, 3, 5]; let first_element = x.get(0); ``` ```rust let x = vec![2, 3, 5]; let first_element = x.first(); ``` -------------------------------- ### Configuration for Allowed Prefixes in Clippy Source: https://rust-lang.github.io/rust-clippy/stable/index This code snippet demonstrates how to configure the `allowed-prefixes` option for a Clippy lint. It specifies a list of prefixes that, when part of an item's name and matching its containing module's name, will not trigger a warning. ```toml allowed-prefixes = [ "to", "from" ] ``` -------------------------------- ### Rust: Use TrailingZeros Over Bit Masks Source: https://rust-lang.github.io/rust-clippy/stable/index Checks for bit mask operations that can be more clearly expressed using the `trailing_zeros()` method. For example, `x & 15 == 0` is less readable than `x.trailing_zeros() >= 4`. ```rust if x & 0b1111 == 0 { } // Use instead: if x.trailing_zeros() >= 4 { } ``` -------------------------------- ### Use `.into()` for tuple-array conversions in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This lint encourages the use of the `.into()` method for converting between tuples and arrays, up to 12 elements. It replaces manual mapping (e.g., `map(|&(a, b)| [a, b])`) with a more concise and intention-revealing `.into()` call. This can simplify code and reduce the chance of subtle bugs. The `msrv` configuration option can be used to specify the minimum Rust version supported. ```rust let t1 = &[(1, 2), (3, 4)]; let v1: Vec<[u32; 2]> = t1.iter().map(|&(a, b)| [a, b]).collect(); ``` ```rust let t1 = &[(1, 2), (3, 4)]; let v1: Vec<[u32; 2]> = t1.iter().map(|&t| t.into()).collect(); ``` -------------------------------- ### Use `vec![0; len]` for efficient vector initialization in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index Highlights inefficient methods for zero-initializing vectors and suggests using the idiomatic `vec![0; len]`. This macro is more efficient as it can leverage specialized allocation and zero-initialization calls, unlike `Vec::new()` followed by `resize` or `extend`. ```rust let mut vec1 = Vec::new(); vec1.resize(len, 0); let mut vec2 = Vec::with_capacity(len); vec2.resize(len, 0); let mut vec3 = Vec::with_capacity(len); vec3.extend(repeat(0).take(len)); // Use instead: let mut vec1 = vec![0; len]; let mut vec2 = vec![0; len]; let mut vec3 = vec![0; len]; ``` -------------------------------- ### Remove unnecessary to_owned calls in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index Identifies redundant calls to `ToOwned::to_owned` and similar functions that result in unnecessary allocations. It provides an example showing how to avoid this by passing the result of `to_string_lossy` directly. ```rust let path = std::path::Path::new("x"); foo(&path.to_string_lossy().to_string()); fn foo(s: &str) {} ``` ```rust let path = std::path::Path::new("x"); foo(&path.to_string_lossy()); fn foo(s: &str) {} ``` -------------------------------- ### Simplify Option cloning in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index Recommends replacing `.as_ref().cloned()` or `.as_mut().cloned()` on `Option` types with a direct clone of the `Option` itself. This simplification makes the code more concise and easier to read. ```rust option.as_ref().cloned() ``` ```rust option.cloned() ``` -------------------------------- ### Use BuildHasher::hash_one for hashing collections in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This lint suggests using the `BuildHasher::hash_one` method when hashing a collection. This method is more concise and potentially more efficient than manually creating a `Hasher`, feeding it the collection, and finishing the hash. It's particularly useful for hashing types that implement `Hash`. ```rust use std::hash::{BuildHasher, Hash, Hasher}; use std::collections::hash_map::RandomState; let s = RandomState::new(); let value = vec![1, 2, 3]; let mut hasher = s.build_hasher(); value.hash(&mut hasher); let hash = hasher.finish(); ``` ```rust use std::hash::BuildHasher; use std::collections::hash_map::RandomState; let s = RandomState::new(); let value = vec![1, 2, 3]; let hash = s.hash_one(&value); ``` -------------------------------- ### Unordered Trait Example (Rust) Source: https://rust-lang.github.io/rust-clippy/stable/index This Rust code snippet illustrates a trait with associated items (consts, type, functions) that are not ordered alphabetically, which would be flagged by the module-item-order lint if configured to check traits. ```rust trait TraitUnordered { const A: bool; const C: bool; const B: bool; type SomeType; fn a(); fn c(); fn b(); } ``` -------------------------------- ### Use expect() directly instead of ok().expect() in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index Recommends calling `expect()` directly on `Result` types rather than first converting to an `Option` with `ok()` and then calling `expect()`. This approach provides more informative error messages when the operation fails. ```rust x.ok().expect("why did I do this again?"); ``` ```rust x.expect("why did I do this again?"); ``` -------------------------------- ### Avoid negative feature names in Rust Cargo.toml Source: https://rust-lang.github.io/rust-clippy/stable/index This lint enforces that feature names in `Cargo.toml` should not be negative, i.e., they should not start with `no-` or `not-`. Features are intended to be additive, and negative names violate this principle. ```toml [features] default = [] no-abc = [] not-def = [] ``` ```toml [features] default = ["abc", "def"] abc = [] def = [] ``` -------------------------------- ### Rust: Detecting useless .as_ref() or .as_mut() calls Source: https://rust-lang.github.io/rust-clippy/stable/index This lint flags the use of `.as_ref()` or `.as_mut()` when the type before and after the call remains the same, indicating an unnecessary operation. The example shows `x.as_ref()` being redundant when `x` itself can be passed directly. ```rust let x: &[i32] = &[1, 2, 3, 4, 5]; do_stuff(x.as_ref()); ``` ```rust let x: &[i32] = &[1, 2, 3, 4, 5]; do_stuff(x); ``` -------------------------------- ### Use String::new() instead of "" - Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This snippet suggests using `String::new()` to create an empty `String` instead of using `""` with methods like `to_string()` or `into()`. This promotes code standardization and avoids potentially confusing variations. The example demonstrates replacing different ways of creating empty strings with `String::new()`. ```rust let a = "".to_string(); let b: String = "".into(); ``` ```rust let a = String::new(); let b = String::new(); ``` -------------------------------- ### Simplify needless borrow in destructuring Source: https://rust-lang.github.io/rust-clippy/stable/index This lint identifies situations where bindings needlessly destructure a reference, borrowing the inner value with '&ref'. The examples demonstrate how to simplify this by directly destructuring the reference without the extra borrow. ```rust let mut v = Vec::::new(); v.iter_mut().filter(|&ref a| a.is_empty()); if let &[ref first, ref second] = v.as_slice() {} // Use instead: let mut v = Vec::::new(); v.iter_mut().filter(|a| a.is_empty()); if let [first, second] = v.as_slice() {} ``` -------------------------------- ### Optimizing Waker Operations with `wake_by_ref` Source: https://rust-lang.github.io/rust-clippy/stable/index Identifies the inefficient pattern of `waker.clone().wake()`. The lint suggests using `waker.wake_by_ref()` instead, which achieves the same result without the overhead of an unnecessary clone and drop operation. ```rust waker.clone().wake(); ``` ```rust waker.wake_by_ref(); ``` -------------------------------- ### Simplify Arithmetic Operations in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index Demonstrates how to replace verbose arithmetic operations with more concise method calls in Rust. This improves readability and leverages built-in optimizations. ```rust use std::f32::consts::E; let a = 3f32; let _ = (2f32).powf(a); let _ = E.powf(a); let _ = a.powf(1.0 / 2.0); let _ = a.log(2.0); let _ = a.log(10.0); let _ = a.log(E); let _ = a.powf(2.0); let _ = a * 2.0 + 4.0; let _ = if a < 0.0 { -a } else { a }; let _ = if a < 0.0 { a } else { -a }; is better expressed as use std::f32::consts::E; let a = 3f32; let _ = a.exp2(); let _ = a.exp(); let _ = a.sqrt(); let _ = a.log2(); let _ = a.log10(); let _ = a.ln(); let _ = a.powi(2); let _ = a.mul_add(2.0, 4.0); let _ = a.abs(); let _ = -a.abs(); ``` -------------------------------- ### Marking Enums as Non-Exhaustive in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This example shows how to mark an enum as non-exhaustive using `#[non_exhaustive]` in Rust. This is a stability commitment, indicating that new variants may be added in the future without breaking existing code. ```rust enum Foo { Bar, Baz } // Use instead: #[non_exhaustive] enum Foo { Bar, Baz } ``` -------------------------------- ### Refactoring Deeply Nested Code in Rust Source: https://rust-lang.github.io/rust-clippy/stable/index This example demonstrates a refactoring technique in Rust to reduce code nesting. It involves extracting nested logic into private functions, improving the overall structure and readability of the code. ```rust // lib.rs pub mod a { pub struct X; impl X { pub fn run(&self) { if true { // etc... } } } } ``` ```rust // a.rs fn private_run(x: &X) { if true { // etc... } } pub struct X; impl X { pub fn run(&self) { private_run(self); } } ``` ```rust // lib.rs pub mod a; ``` -------------------------------- ### Correcting Almost Complete Character Ranges (Rust) Source: https://rust-lang.github.io/rust-clippy/stable/index Identifies and corrects half-open character ranges that likely intended to be inclusive. For example, `'a'..'z'` is often a typo for `'a'..='z'`, which includes all characters from 'a' to 'z'. ```rust let _ = 'a'..='z'; ``` -------------------------------- ### Use Option::as_slice instead of manual implementations Source: https://rust-lang.github.io/rust-clippy/stable/index Detects various manual reimplementations of `Option::as_slice`. It points out that these manual implementations are more complex and less performant than using the built-in `as_slice` method. ```rust _ = opt.as_ref().map_or(&[][..], std::slice::from_ref); _ = match opt.as_ref() { Some(f) => std::slice::from_ref(f), None => &[], }; ``` ```rust _ = opt.as_slice(); _ = opt.as_slice(); ``` -------------------------------- ### Consistent `pub` Visibility Shorthand (Rust) Source: https://rust-lang.github.io/rust-clippy/stable/index Enforces consistency in the usage of `pub()` visibility modifiers. It specifically targets the `pub(super)` shorthand, recommending its use or avoidance based on project-wide style guides. ```rust pub(super) type OptBox = Option>; ``` -------------------------------- ### Rust: Using &raw const and &raw mut for pointer casting Source: https://rust-lang.github.io/rust-clippy/stable/index Demonstrates the use of `&raw const` and `&raw mut` as a more readable alternative to casting references to raw pointers with `as *const T` or `as *mut T`. ```rust let val = 1; let p = &val as *const i32; let mut val_mut = 1; let p_mut = &mut val_mut as *mut i32; ``` ```rust let val = 1; let p = &raw const val; let mut val_mut = 1; let p_mut = &raw mut val_mut; ```