rust-lang / rust-lang/rust-clippy
Possibly missing lint: `"some text".to_string().as_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
Catches instances where you use as_str() directly after to_string():
fn main() {
// This doesn't get linted by clippy, but it seems like it should?
println!("{}", "🧑🚀It's a str? Always has been 🔫🧑🚀".to_string().as_str());
}
And possibly also offers an auto-fix for this (just removing both method calls):
fn main() {
// This doesn't get linted by clippy, but it seems like it should?
println!("{}", "🧑🚀It's a str? Always has been 🔫🧑🚀");
}
Advantage
This isn't exactly something that you'd likely write verbatim, but I had it come up after a number of edits and simplifications where initially the to_string and then the as_str were justified, but after removing a bunch of format!s the code was simplified down. I was kinda surprised to see that clippy didn't tidy this up for me (usually it's really good at this sorta thing!).
The original code was something like:
function_that_expects_a_str(format!("some string with a variable: {}", var).as_str());
but then I no longer needed to use a variable, so removed it:
function_that_expects_a_str(format!("some string without a variable").as_str());
At which point clippy noted I shouldn't use format!, and it got replaced with a to_string():
function_that_expects_a_str("some string without a variable".to_string().as_str());
And thus we're left with .to_string().as_str()
Drawbacks
It's definitely a small ask, and I don't imagine it would come up very often. But given that clippy's lints got me to this place, it seems a bit weird that I should be going in to manually tidy things up afterwards.
Example
fn main() {
println!("{}", "🧑🚀It's a str? Always has been 🔫🧑🚀".to_string().as_str());
}
Could be written as:
fn main() {
println!("{}", "🧑🚀It's a str? Always has been 🔫🧑🚀");
}
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
No implementation file or test is named. Start by locating the relevant Clippy lint implementation and its tests, then use the Rust examples to define the pattern; done means the redundant .to_string().as_str() form is diagnosed and its intended simplified form is covered by tests.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100