rust-lang / rust-lang/rust-clippy

should_implement_trait should not be triggered by from_str with explicit type annotation

Open
#1,731 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

warning: defining a method called `from_str` on this type; consider implementing the `std::str::FromStr` trait or choosing a less ambiguous name
   --> src/lib.rs:222:5
    |
222 | /     pub fn from_str(s: &'a str) -> Result<JID<'a>> {
223 | |         if s == "" {
224 | |             return Err(Error::EmptyJID);
225 | |         }
...   |
305 | |         JID::new(lpart, dpart.trim_right_matches('.'), rpart)
306 | |     }
    | |_____^
    |
    = note: #[warn(should_implement_trait)] on by default
    = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#should_implement_trait

For types that require an explicit type annotation, it is sometimes impossible to implement FromStr because its argument does not have a type annotation. For instance, consider the following:

use std::borrow;
use std::str;

struct JID<'a> {
    local: borrow::Cow<'a, str>,
}

struct DummyErr {}

impl<'a> str::FromStr for JID<'a> {
    type Err = DummyErr;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // We can not guarantee that s lives longer than 'a
        Ok(JID { local: s.into() })
    }
}

Since we can never guarantee that the &str lives longer than 'a, FromStr cannot be implemented for this type.

Naming the method something else goes against the API guidelines (although admittedly it is confusing naming it the same thing as a method on a common trait).

Related: #1600

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 by reproducing the warning from the src/lib.rs example and read the discussion in related issue #1600. Trace the should_implement_trait lint's handling of an explicitly annotated type and lifetime-bearing from_str method; done means this valid case no longer triggers the warning without weakening detection of ambiguous methods.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.