Skip to content

Unnecessary call to to_string when the underlying type implements AsRef<str> #7933

@smoelius

Description

@smoelius

What it does

Checks for expressions of the form &X.to_string(), used in a position requiring a &str, where X implements AsRef<str>.

In such a case, the call to to_string is unnecessary.

Similar to to_string/AsRef<str>, there's also to_path_buf/AsRef<Path> and to_vec/AsRef<[T]>.

There are probably others.

I am happy to tackle this if we can agree on the check, and whether it is useful.

Categories (optional)

  • Kind: perf

Drawbacks

Potential "false positives" if X's AsRef<str> and to_string implementations produce different strings. But I would expect such cases to be rare.

Example

use std::{fmt::Write, io::Write as OtherWrite};

fn main() {
    let mut s = String::new();
    let dir = std::env::current_dir().unwrap();
    s.write_str(&dir.to_string_lossy().to_string()).unwrap();
    //                                ^^^^^^^^^^^^ unnecessary
    s.write_str(" is the current directory.\n").unwrap();
    std::io::stdout().write(s.as_bytes()).unwrap();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions