Skip to content

Detect unnecessary copies with functions taking impl Into<String> #16109

@aticu

Description

@aticu

What it does

When calling a function with an impl Into<String> parameter with a &str derived from a String that is not used later, an unnecessary copy of the value will be made inside of the function. This could be avoided by passing the String directly.

The same applies (at least) to the following types:

  • Vec<T> and &[T]
  • Box<T> and T

Advantage

With this lint unnecessary copies of heap-based value can be avoided.

Drawbacks

Code could be intentionally structured to only pass values by reference for consistency purposes. For example in macros.

Example

fn main() {
    takes_into_string(&*format!("some long {}", "string"));
}

fn takes_into_string(s: impl Into<String>) {
    println!("{}", s.into());
}

Could be written as:

fn main() {
    takes_into_string(format!("some long {}", "string"));
}

fn takes_into_string(s: impl Into<String>) {
    println!("{}", s.into());
}

Comparison with existing lints

Unlike clippy::needless-borrows-for-generic-args this would also find more sophisticated patterns (specifically &* instead of &). Alternatively this lint could be extended to support that.

Additional Context

No response

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