rust-lang / rust-lang/rust-clippy
Suggest `impl FromStr` instead of `TryFrom<&str>`
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
Looks for impl TryFrom<&str> and suggest impl FromStr instead
Advantage
When parsing a string, FromStr is the idiomatic trait to implement, but that may not be immediately obvious to a Rust novice.
From the docs of TryFrom:
(TryFrom) is useful when you are doing a type conversion that may trivially succeed but may also need special handling
Parsing is something else completely, and for that trait FromStr is to be used.
See also @kangalio's comment on the inverse issue.
Drawbacks
If there is a lifetime on the type, then FromStr won't work, and so we should not make the suggestion in that cade.
Example
impl TryFrom<&str> for MyType {
type Error = MyError;
fn try_from(value: &strr) -> Result<Self, Self::Error> {
Could be written as:
impl FromStr MyType {
type Err = MyError;
fn from_str(value: &strr) -> Result<Self, Self::Err> {
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the linked inverse issue #5588 and the existing Clippy lint patterns for trait suggestions. Define the lifetime exception and diagnostic wording from the examples, then add coverage showing the suggestion for TryFrom<&str> and no suggestion when the type has a lifetime.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 54/100