rust-lang / rust-lang/rust-clippy

Suggest replacing `split(...).collect().rev()` with `rsplit()`

Open
#11,632 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

A user working with a string might forget that str::rsplit exists, and design an API like this:

     /// Returns this DNS name's labels, in reversed order
     /// (from top-level domain to most-specific subdomain).
     fn rlabels(&self) -> impl Iterator<Item = &'_ str> {
        self.as_str()
            .split('.')
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
     }

which could be rewritten as:

    /// Returns this DNS name's labels, in reversed order
    /// (from top-level domain to most-specific subdomain).
    fn rlabels(&self) -> impl Iterator<Item = &'_ str> {
        self.as_str().rsplit('.')
    }

Clippy does not currently detect this.

Advantage
  • Simpler (fewer functions invoked)
  • Fewer internal iterator transforms
  • Fewer allocations (no round-trip through a Vec<_> or other owned container type)
  • Reuses an intended standard API instead of reimplementing it
Drawbacks

None that I can think of.

Example
mystr.split('.').collect::<Vec<_>>.into_iter().rev()

Could be written as:

mystr.rsplit('.')

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start from the issue's split(...).collect::<Vec<_>>().into_iter().rev() example and locate Clippy's existing iterator-chain lint entry points and tests. Define the supported equivalent patterns and verify that the lint suggests rsplit() only where the transformation preserves behavior, with tests covering the accepted and rejected cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.