Open
Description
What it does
Look at the following code:
fn open(path: impl AsRef<str>) {}
fn main() {
let path = "test.txt".to_string();
open(path);
}
Here, we create some string with hard-coded value, and pass it to a function. As we can see, this variable is used only to pass it to open
function, and as we see from open
signature, it can work both with &str
and String
, so .to_string()
here is unnecessary.
I suggest to add lint which hints that .to_string()
after hardcoded &str
can be removed if it can be removed.
Advantage
- eliminates unnecessary allocation and copy
- makes code a bit easier to read
Drawbacks
Probably some functions can behave different depending on &str
or String
was passed (however, I think such functions are bad practice). Thus, this lint maybe should be in pedantic group or so.
Example
fn open(path: impl AsRef<str>) {}
fn main() {
let path = "test.txt".to_string();
open(path);
}
Could be written as:
fn open(path: impl AsRef<str>) {}
fn main() {
let path = "test.txt";
open(path);
}