### indexing_slicing: Good example with get methods Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended alternative using `get` methods which return `Option` and do not panic, allowing explicit handling of out-of-bounds cases. ```rust x.get(2); x.get(100); x.get(2..100); let i = 10; let j = 20; y.get(i..j); ``` -------------------------------- ### Configuration example for allowed-wildcard-imports Source: https://rust-lang.github.io/rust-clippy/master/index.html Example configuration for the 'allowed-wildcard-imports' option, listing path segments allowed to have wildcard imports. ```toml allowed-wildcard-imports = [ "utils", "common" ] ``` -------------------------------- ### non_zero_suggestions: Example of converting NonZero to regular integer Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the problematic conversion from NonZeroU32 to u64 using get() before division and modulo operations. This is flagged by the lint. ```rust use std::num::{NonZeroU32, NonZeroU64}; fn example(x: u64, y: NonZeroU32) { // Bad: Converting NonZeroU32 to u64 unnecessarily let r1 = x / u64::from(y.get()); let r2 = x % u64::from(y.get()); } ``` -------------------------------- ### arithmetic-side-effects-allowed-binary configuration example Source: https://rust-lang.github.io/rust-clippy/master/index.html Configuration example for the arithmetic-side-effects-allowed-binary option, showing asymmetric pairs and wildcard support. ```toml arithmetic-side-effects-allowed-binary = [["SomeType" , "f32"], ["AnotherType", "*"]] ``` -------------------------------- ### needless_late_init: Late initialization examples Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows three examples of late initialization that can be replaced by a let statement with an initializer. ```rust let a; a = 1; let b; match 3 { 0 => b = "zero", 1 => b = "one", _ => b = "many", } let c; if true { c = 1; } else { c = -1; } ``` -------------------------------- ### create_dir: Example of std::fs::create_dir Source: https://rust-lang.github.io/rust-clippy/master/index.html Example showing the discouraged usage of std::fs::create_dir, which can fail when multiple directories need to be created or when the directory already exists. ```rust std::fs::create_dir("foo"); ``` -------------------------------- ### arithmetic-side-effects-allowed configuration example Source: https://rust-lang.github.io/rust-clippy/master/index.html Configuration example for the arithmetic-side-effects-allowed option, listing type names to suppress checking. ```toml arithmetic-side-effects-allowed = ["SomeType", "AnotherType"] ``` -------------------------------- ### arithmetic-side-effects-allowed-unary configuration example Source: https://rust-lang.github.io/rust-clippy/master/index.html Configuration example for the arithmetic-side-effects-allowed-unary option, listing type names for unary operations. ```toml arithmetic-side-effects-allowed-unary = ["SomeType", "AnotherType"] ``` -------------------------------- ### expect_used: Configuration example for allow-unwrap-types Source: https://rust-lang.github.io/rust-clippy/master/index.html Example configuration for the allow-unwrap-types option, which lists types that are allowed to use unwrap() and expect() on. The default is an empty list. ```toml allow-unwrap-types = [ "std::sync::LockResult" ] ``` -------------------------------- ### std_instead_of_core: Example using std::hash::Hasher Source: https://rust-lang.github.io/rust-clippy/master/index.html Example showing the problematic import of Hasher from std. This lint is restricted to crates that want no_std compatibility. ```rust use std::hash::Hasher; ``` -------------------------------- ### absolute_paths: Example of absolute path usage Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows an example of using an absolute path like `std::f64::consts::PI`, which the lint flags. This is the problematic code that should be replaced with a `use` statement or shorter paths. ```rust let x = std::f64::consts::PI; ``` -------------------------------- ### cast_lossless: Example using `u64::from` Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended replacement for the previous example, using `u64::from(x)` instead of `x as u64`. This conversion function is lossless and makes the intent clear. ```rust fn as_u64(x: u8) -> u64 { u64::from(x) } ``` -------------------------------- ### duration_suboptimal_units: Good example using larger time units Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended replacement using larger units: from_secs, from_mins, and from_hours. This is the corrected version of the previous example. ```rust use std::time::Duration; let dur = Duration::from_secs(50); let dur = Duration::from_mins(30); let dur = Duration::from_hours(10); ``` -------------------------------- ### format_in_format_args: Bad example with nested format! Source: https://rust-lang.github.io/rust-clippy/master/index.html Example that triggers the lint: uses format! inside println! arguments, causing an unnecessary temporary allocation. ```rust println!("error: {}", format!("something failed at {}", Location::caller())); ``` -------------------------------- ### pathbuf_init_then_push: Good alternatives using from and join Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended alternatives to the bad pattern: using PathBuf::from or chaining join on a new PathBuf. ```rust let path_buf = PathBuf::from("foo"); // or let path_buf = PathBuf::new().join("foo"); ``` -------------------------------- ### needless_collect: Example of unnecessary collect Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows collecting an iterator into a Vec just to get its length, which is unnecessary. ```rust let len = iterator.collect::>().len(); ``` -------------------------------- ### needless_nonzero_get: Bad example with division operator Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the problematic pattern where `get()` is used in a division operation. ```rust let _ = 4 / nz.get(); ``` -------------------------------- ### format_push_string: Good example using write! Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended replacement using write! with an ignored Result, avoiding the extra allocation. Requires importing std::fmt::Write as _. ```rust use std::fmt::Write as _; // import without risk of name clashing let mut s = String::new(); let _ = write!(s, "0x{:X}", 1024); ``` -------------------------------- ### needless_nonzero_get: Bad example with leading_zeros Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the problematic pattern where `get()` is called on a NonZero value before calling a method that NonZero provides directly. ```rust let _ = nz.get().leading_zeros(); ``` -------------------------------- ### empty_docs: Good example without empty doc comment Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended code without the empty documentation comment. ```rust fn returns_true() -> bool { true } ``` -------------------------------- ### coerce_container_to_any: Good example using dereference Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the correct approach by dereferencing the Box to get a reference to the inner dyn Any, allowing downcast to succeed. ```rust let x: Box = Box::new(0u32); let dyn_any_of_u32: &dyn Any = &*x; // Succeeds since we have a &dyn Any to the inner u32! assert_eq!(dyn_any_of_u32.downcast_ref::(), Some(&0u32)); ``` -------------------------------- ### chunks_exact_to_as_chunks: Good example using as_chunks Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended alternative using as_chunks::<2>() which returns arrays for better ergonomics and type safety. ```rust let slice = [1, 2, 3, 4, 5, 6]; let (chunks, remainder) = slice.as_chunks::<2>(); for chunk in chunks {} ``` -------------------------------- ### explicit_deref_methods: Example of explicit deref() call Source: https://rust-lang.github.io/rust-clippy/master/index.html Code that triggers explicit_deref_methods: using a.deref() to get a &str from a &mut String. The lint suggests using &*a instead. ```rust use std::ops::Deref; let a: &mut String = &mut String::from("foo"); let b: &str = a.deref(); ``` -------------------------------- ### Using Waker::noop() (good example) Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended replacement using Waker::noop() to create a no-op waker. ```rust use std::task::Waker; let waker = Waker::noop(); ``` -------------------------------- ### duration_subsec: Bad example calculating subsecond units manually Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows manual division of subsec_nanos() to get microseconds and milliseconds, which the lint flags as less concise. ```rust let micros = duration.subsec_nanos() / 1_000; let millis = duration.subsec_nanos() / 1_000_000; ``` -------------------------------- ### join_absolute_paths: Example of Path::join with leading separator Source: https://rust-lang.github.io/rust-clippy/master/index.html Demonstrates the problematic case where joining a path starting with a separator overwrites the original path, resulting in "/sh". ```rust let path = Path::new("/bin"); let joined_path = path.join("/sh"); assert_eq!(joined_path, PathBuf::from("/sh")); ``` -------------------------------- ### pathbuf_init_then_push: Bad example with push after new Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the problematic pattern: creating a PathBuf and then calling push. The lint suggests using PathBuf::from or join instead. ```rust let mut path_buf = PathBuf::new(); path_buf.push("foo"); ``` -------------------------------- ### for_unbounded_range: Example of unbounded range Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows an unbounded range starting at 250u8, which can cause panics or infinite loops due to overflow. The lint suggests setting a max value. ```rust for i in 250u8.. { println!("{i}"); } ``` -------------------------------- ### seek_from_current: Example of seek(SeekFrom::Current(0)) Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the problematic use of seek(SeekFrom::Current(0)) to get the current stream position, which the lint suggests replacing with stream_position. ```rust use std::fs::File; use std::io::{self, Write, Seek, SeekFrom}; fn main() -> io::Result<()> { let mut f = File::create("foo.txt")?; f.write_all(b"Hello")?; eprintln!("Written {} bytes", f.seek(SeekFrom::Current(0))?); Ok(()) } ``` -------------------------------- ### option_env_unwrap: Good example with env!() Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the compile-time safe alternative using env!. Use this to replace option_env!().unwrap(). ```rust let _ = env!("HOME"); ``` -------------------------------- ### doc_nested_refdefs: Example of link reference definition in list item Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows a link reference definition at the start of a list item, which triggers the lint. The definition is likely intended as an intra-doc link. ```rust //! - [link]: description ``` -------------------------------- ### chars_next_cmp: Problematic usage of chars().next() Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of code that triggers the chars_next_cmp lint: using chars().next() to check if a string starts with a given char. This is flagged as style warn and is machine applicable. ```rust let name = "foo"; if name.chars().next() == Some('_') {}; ``` -------------------------------- ### create_dir: Use std::fs::create_dir_all instead Source: https://rust-lang.github.io/rust-clippy/master/index.html Recommended replacement using std::fs::create_dir_all to avoid failures when creating multiple directories or when the directory already exists. ```rust std::fs::create_dir_all("foo"); ``` -------------------------------- ### reversed_empty_ranges: Example of problematic reversed range Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows a range expression (10..=0) that is empty because the start is greater than the end, and a slice index (3..1) that will panic at runtime. This triggers the reversed_empty_ranges lint. ```rust fn main() { (10..=0).for_each(|x| println!("{}", x)); let arr = [1, 2, 3, 4, 5]; let sub = &arr[3..1]; } ``` -------------------------------- ### module_name_repetitions: Configuration example for allowed-prefixes Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows how to configure the allowed-prefixes option for this lint, using a TOML array. ```toml allowed-prefixes = [ "to", "from" ] ``` -------------------------------- ### bytes_nth: Good example using .as_bytes().get() Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended replacement for `.bytes().nth()`: `.as_bytes().get()` is more efficient and readable. ```rust "Hello".as_bytes().get(3); ``` -------------------------------- ### inefficient_to_string: Example of inefficient and efficient to_string() calls Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the problematic pattern of calling to_string() on &&str (slow) and the correct pattern using &s to get &str (fast). The comment indicates the generic implementation for T: Display is used in the slow case. ```rust // Generic implementation for `T: Display` is used (slow) ["foo", "bar"].iter().map(|s| s.to_string()); // OK, the specialized impl is used ["foo", "bar"].iter().map(|&s| s.to_string()); ``` -------------------------------- ### Ordered trait example Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of a trait with items in the correct alphabetical order, used as the recommended alternative to the unordered example. ```rust trait TraitOrdered { const A: bool; const B: bool; const C: bool; type SomeType; fn a(); fn b(); fn c(); } ``` -------------------------------- ### Configure module item order groupings Source: https://rust-lang.github.io/rust-clippy/master/index.html Example configuration for `module-item-order-groupings` that places modules and use statements at the top, with all other items in an 'everything_else' group. ```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", ], ], ] ``` -------------------------------- ### renamed_function_params: Configuration example for allow-renamed-params-for Source: https://rust-lang.github.io/rust-clippy/master/index.html Example configuration showing how to ignore a specific trait path for the lint. ```toml allow-renamed-params-for = [ "std::convert::From" ] ``` -------------------------------- ### ip_constant: Good example using predefined IP constants Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended replacement for ip_constant: use Ipv4Addr::LOCALHOST and Ipv6Addr::LOCALHOST instead of explicit addresses. ```rust use std::net::{Ipv4Addr, Ipv6Addr}; // IPv4 loopback let addr_v4 = Ipv4Addr::LOCALHOST; // IPv6 loopback let addr_v6 = Ipv6Addr::LOCALHOST; ``` -------------------------------- ### Allowed alternative type example Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of a similar type that is allowed by the configuration, shown as a replacement suggestion. ```rust // A similar type that is allowed by the config use std::collections::HashMap; ``` -------------------------------- ### trivial_regex: Good example Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows using str::starts_with instead of a trivial regex. ```rust str::starts_with("foobar") ``` -------------------------------- ### manual_ilog2: Example of manual ilog2 implementation Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the problematic patterns: using leading_zeros or ilog(2) to compute the base-2 logarithm. ```rust let x: u32 = 5; let log = 31 - x.leading_zeros(); let log = x.ilog(2); ``` -------------------------------- ### rc_clone_in_vec_init: Recommended alternatives Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows two recommended alternatives for the rc_clone_in_vec_init lint: initializing each value separately with a loop, or creating the reference beforehand and cloning it explicitly. ```rust // Initialize each value separately: let mut data = Vec::with_capacity(100); for _ in 0..100 { data.push(std::rc::Rc::new("some data".to_string())); } // Or if you want clones of the same reference, // Create the reference beforehand to clarify that // it should be cloned for each value let data = std::rc::Rc::new("some data".to_string()); let v = vec![data; 100]; ``` -------------------------------- ### char_indices_as_byte_indices: Good example using char_indices() Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended alternative using char_indices() which yields byte indices and avoids panics. ```rust for (idx, c) in s.char_indices() { let _ = s[idx..]; } ``` -------------------------------- ### suboptimal_flops: Improved floating-point expressions using built-in methods Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended replacement for the previous example, using methods like exp2, exp, sqrt, log2, log10, ln, powi, mul_add, and abs. ```rust 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(); ``` -------------------------------- ### upper_case_acronyms: Example of fully capitalized name Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of a struct name with fully capitalized acronym, which the lint warns about. ```rust struct HTTPResponse; ``` -------------------------------- ### unwrap_used: Example of unwrap calls Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of code that uses unwrap() on Option and Result, which the lint warns about because it can panic. ```rust option.unwrap(); result.unwrap(); ``` -------------------------------- ### assigning_clones: Good example using clone_from() Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the corrected code that uses clone_from to avoid unnecessary allocations. ```rust struct Thing; impl Clone for Thing { fn clone(&self) -> Self { todo!() } fn clone_from(&mut self, other: &Self) { todo!() } } pub fn assign_to_ref(a: &mut Thing, b: Thing) { a.clone_from(&b); } ``` -------------------------------- ### unwrap_in_result: Before example with expect() Source: https://rust-lang.github.io/rust-clippy/master/index.html Before example for the unwrap_in_result lint: a function returning Result uses expect(), which can panic on error. ```rust fn divisible_by_3(i_str: String) -> Result<(), String> { let i = i_str .parse::() .expect("cannot divide the input by three"); if i % 3 != 0 { Err("Number is not divisible by 3")? } Ok(()) } ``` -------------------------------- ### Idiomatic alternative using utility methods Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended replacement: using `is_ok()`, `is_err()`, `is_none()`, `is_some()`, `is_pending()`, `is_ready()`, `is_ipv4()`, `is_ipv6()`, or direct condition checks. This is more concise and clear. ```rust if Ok::(42).is_ok() {} if Err::(42).is_err() {} if None::<()>.is_none() {} if Some(42).is_some() {} if Poll::Pending::<()>.is_pending() {} if Poll::Ready(42).is_ready() {} if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {} if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {} Ok::(42).is_ok(); let cond = true; if cond {} cond; ``` -------------------------------- ### large_digit_groups: example Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of a constant with digit groups that are too large, triggering the lint. The grouping negatively impacts readability. ```rust let x: u64 = 6186491_8973511; ``` -------------------------------- ### search_is_some: Use instead example with any/contains Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended concise alternatives using any() and contains() instead of search followed by is_some() or is_none(). ```rust let vec = vec![1]; vec.iter().any(|x| *x == 0); !"hello world".contains("world"); ``` -------------------------------- ### Unordered trait example Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of a trait with items in an unordered arrangement, used to illustrate the lint's detection. ```rust trait TraitUnordered { const A: bool; const C: bool; const B: bool; type SomeType; fn a(); fn c(); fn b(); } ``` -------------------------------- ### suspicious_op_assign_impl lint example Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of the suspicious_op_assign_impl lint. The code subtracts in an `AddAssign` impl, which is likely a typo or copy-and-paste error. ```rust impl AddAssign for Foo { fn add_assign(&mut self, other: Foo) { *self = *self - other; } } ``` -------------------------------- ### duration_subsec: Good example using dedicated methods Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended direct calls to subsec_micros() and subsec_millis() instead of manual calculations. ```rust let micros = duration.subsec_micros(); let millis = duration.subsec_millis(); ``` -------------------------------- ### manual_repeat_n: repeat().take() example Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of using repeat().take() which can be replaced with repeat_n(). This pattern is flagged by the manual_repeat_n lint. ```rust let _ = std::iter::repeat(10).take(3); ``` -------------------------------- ### into_iter_on_ref: Good example using iter instead Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended replacement for the into_iter_on_ref lint. Use iter or iter_mut directly on the reference. ```rust (&vec).iter(); ``` -------------------------------- ### crosspointer_transmute: Example of transmute between type and pointer Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of a transmute between a type T and a pointer to that type, which is easy to mistake and is flagged by this lint. ```rust core::intrinsics::transmute(t) // where the result type is the same as // `*t` or `&t`'s ``` -------------------------------- ### unwrap_in_result: After example with map_err() Source: https://rust-lang.github.io/rust-clippy/master/index.html After example for the unwrap_in_result lint: the function uses map_err() to convert the parse error into a String, avoiding a panic. ```rust fn divisible_by_3(i_str: String) -> Result<(), String> { let i = i_str .parse::() .map_err(|e| format!("cannot divide the input by three: {}", e))?; if i % 3 != 0 { Err("Number is not divisible by 3")? } Ok(()) } ``` -------------------------------- ### similar_names: Example 2 with similar names Source: https://rust-lang.github.io/rust-clippy/master/index.html Another example of similar names that differ by one character, triggering the similar_names lint. ```rust let orange = val; let ornange = val2; ``` -------------------------------- ### self_named_constructors: Good example with constructor named new Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended alternative: naming the constructor `new` instead of `foo` to avoid repeating the type name. ```rust struct Foo {} impl Foo { pub fn new() -> Foo { Foo {} } } ``` -------------------------------- ### inherent_to_string: Example of inherent to_string method Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows an example that triggers the 'inherent_to_string' lint: defining an inherent 'to_string' method on a struct. ```rust pub struct A; impl A { pub fn to_string(&self) -> String { "I am A".to_string() } } ``` -------------------------------- ### unwrap_or_default: Example of unwrap_or with default Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of code that uses unwrap_or and or_insert_with with default values, which the lint suggests replacing with unwrap_or_default and or_default. ```rust x.unwrap_or(Default::default()); map.entry(42).or_insert_with(String::new); ``` -------------------------------- ### vec_init_then_push: Example of Vec::new() followed by push calls Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the inefficient pattern of creating a Vec with Vec::new() and then pushing elements individually. ```rust let mut v = Vec::new(); v.push(0); v.push(1); v.push(2); ``` -------------------------------- ### manual_retain: filter().collect() example Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of using filter().collect() to filter a vector, which can be replaced with retain(). This pattern is flagged by the manual_retain lint. ```rust let mut vec = vec![0, 1, 2]; vec = vec.iter().filter(|&x| x % 2 == 0).copied().collect(); vec = vec.into_iter().filter(|x| x % 2 == 0).collect(); ``` -------------------------------- ### infinite_loop: Corrected example with break condition Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows an alternative correction for the infinite loop example by adding a 'break' condition to exit the loop. ```rust fn run_forever() { loop { // do something if condition { break; } } } ``` -------------------------------- ### cmp_null: Good example using `.is_null()` Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended replacement using the inherent `.is_null()` method for readability. ```rust if x.is_null() { // .. } ``` -------------------------------- ### Disallowed type usage example Source: https://rust-lang.github.io/rust-clippy/master/index.html Example of using a disallowed type (`BTreeMap`) that would trigger the lint. Shows both an import and a direct usage. ```rust use std::collections::BTreeMap; // or its use let x = std::collections::BTreeMap::new(); ``` -------------------------------- ### manual_strip: Bad example using starts_with and slicing Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the non-idiomatic pattern that triggers the manual_strip lint. It uses starts_with and then slices the string using the pattern's length, which can panic and is less readable. ```rust let s = "hello, world!"; if s.starts_with("hello, ") { assert_eq!(s["hello, ".len()..].to_uppercase(), "WORLD!"); } ``` -------------------------------- ### disallowed_fields: Example clippy.toml configuration Source: https://rust-lang.github.io/rust-clippy/master/index.html Example configuration for the disallowed-fields lint, showing how to specify fields as strings or inline tables with optional reason. ```toml disallowed-fields = [ # Can use a string as the path of the disallowed field. "std::ops::Range::start", # Can also use an inline table with a `path` key. { path = "std::ops::Range::start" }, # When using an inline table, can add a `reason` for why the field # is disallowed. { path = "std::ops::Range::start", reason = "The start of the range is not used" }, ] ``` -------------------------------- ### manual_find_map: Bad example Source: https://rust-lang.github.io/rust-clippy/master/index.html Using find followed by map, which can be simplified to find_map. ```rust (0_i32..10) .find(|n| n.checked_add(1).is_some()) .map(|n| n.checked_add(1).unwrap()); ``` -------------------------------- ### option_as_ref_cloned: Good example with clone() Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the concise fix by cloning the Option directly. Use this to replace the as_ref().cloned() pattern. ```rust fn foo(bar: &Option>) -> Option> { bar.clone() } ``` -------------------------------- ### dbg_macro: Example of dbg! macro usage Source: https://rust-lang.github.io/rust-clippy/master/index.html Example showing the discouraged usage of the dbg! macro, which is intended for debugging and should not be present in released software. ```rust dbg!(true) ``` -------------------------------- ### Example of missing_inline_in_public_items lint Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows a Rust code example that triggers the `missing_inline_in_public_items` lint. The example includes public functions without `#[inline]`, trait methods with default implementations, and public methods in a public struct that are missing `#[inline]`. Items that are private or already marked `#[inline]` are considered okay. ```rust pub fn foo() {} // missing #[inline] fn ok() {} // ok #[inline] pub fn bar() {} // ok #[inline(always)] pub fn baz() {} // ok pub trait Bar { fn bar(); // ok fn def_bar() {} // missing #[inline] } struct Baz; impl Baz { fn private() {} // ok } impl Bar for Baz { fn bar() {} // ok - Baz is not exported } pub struct PubBaz; impl PubBaz { fn private() {} // ok pub fn not_private() {} // missing #[inline] } impl Bar for PubBaz { fn bar() {} // missing #[inline] fn def_bar() {} // missing #[inline] } ``` -------------------------------- ### bool_assert_comparison: Good example using assert! Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended alternative: using assert! with the negated boolean expression. ```rust assert!(!"a".is_empty()); ``` -------------------------------- ### try_from_instead_of_from_str: Example of TryFrom<&str> implementation Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows a typical `TryFrom<&str>` implementation that could be replaced with `FromStr`. The `try_from` method is empty in this example. ```rust impl TryFrom<&str> for MyType { type Error = MyError; fn try_from(value: &str) -> Result { } } ``` -------------------------------- ### clear_with_drain: Good example using clear() Source: https://rust-lang.github.io/rust-clippy/master/index.html Shows the recommended alternative using .clear() which is more efficient and clearer in intent. ```rust let mut v = vec![1, 2, 3]; v.clear(); ```