Rust

Rust

Made by DeepSource

Found possibly misused .splitn(..) RS-W1067

Anti-pattern
Minor

Using .splitn(..) or .rsplitn(..) with n set to 1 or 0, is a no-op. The argument refers to the number of items to be returned, and not the number of splits.

Thus:

  • splitn(1, ..) returns the string itself as a whole.
  • splitn(0, ..) returns an empty SplitN iterator.

Bad practice

let sentence = "Mary had a little lambda";
for word in sentence.splitn(1, ' ') {
    // ...
}

Recommended

let sentence = "Mary had a little lambda";
match sentence.split_once(' ') {
    Some((first, rest)) => /* ... */
    _ => /* ... */
}