Skip to content

Lint slice args that could be slices of impl Deref<_>s #7587

@llogiq

Description

@llogiq

What it does

On exported functions, lint function arguments of the following types: &[&str], &[String], &[&[_]], &[Vec<_>] . Suggest using &[impl Deref<Target = str>] and &[impl Deref<Target = [_]>] as appropriate. The lint is subject to the avoid-breaking-exported-api configuration.

Categories (optional)

  • Kind: perf

Why is this bad?

&[&str] and &[&[_]] require extra backing space if we already have a Vec<String> or Vec<Vec<_>>. On the other hand, &[String] and &[Vec<_>] require that we allocate to change the type if we actually have a Vec<&str>, a Vec<Cow<'_, str>> or a Vec<Arc<[_]>>`.

Drawbacks

The resulting code is less terse and the generics mean more work for type inference. Worst case some client code might fail to compile because inference no longer gets a clear argument type to work with.

Example

fn takes_strings(strings: &[String]) { todo!() }
fn takes_strs(strs: &[&str]) { todo!() }
fn takes_vecs(vecs: &[Vec<u8>]) { todo!() }
fn takes_slices(slices: &[&[u8]]) { todo!() }

Could be written as:

fn takes_strings(strings: &[impl Deref<Target = str>]) { todo!() }
fn takes_strs(strs: &[impl Deref<Target = str>]) { todo!() }
fn takes_vecs(vecs: &[impl Deref<Target = [u8]>]) { todo!() }
fn takes_slices(slices: &[impl Deref<Target = [u8]>]) { todo!() }

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions