Skip to content

single_range_in_vec_init stronger than expected, when type is known #11086

Open
@matzemathics

Description

@matzemathics

Summary

The single_range_in_vec_init warning seems a bit overly cautious, if the type resulting from an invocation of a vec! macro is already known "from the outside", e.g. via a type annotation or when it is used as an argument / return value.

For example

let foo: Vec<Range<usize>> = vec![1..5]; // causes "warning: a `Vec` of `Range` that is only one element"

In this case clippy might infer, that the user indeed wanted a Vec<Range<...>>, because otherwise the program could not even have type checked. The same is true for this example:

fn barify(v: Vec<Range<usize>>) {
  ...
}

let v = vec![3..42]; // causes "warning: a `Vec` of `Range` that is only one element"
barify(v);

One explicit way to remedy this is using explicit lengths:

let foo = vec![1..5; 1]; // OK

although I am slightly worried that tools like cargo-fmt might at some point opt to remove that.

Lint Name

single_range_in_vec_init

Reproducer

I tried this code:

use std::ops::Range;

fn main() {
    let _foo: Vec<Range<usize>> = vec![1..5];
}

I saw this happen:

warning: a `Vec` of `Range` that is only one element
 --> src/main.rs:4:35
  |
4 |     let _foo: Vec<Range<usize>> = vec![1..5];
  |                                   ^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_range_in_vec_init
  = note: `#[warn(clippy::single_range_in_vec_init)]` on by default
help: if you wanted a `Vec` that contains the entire range, try
  |
4 |     let _foo: Vec<Range<usize>> = (1..5).collect::<std::vec::Vec<usize>>();
  |                                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
help: if you wanted a `Vec` of len 5, try
  |
4 |     let _foo: Vec<Range<usize>> = vec![1; 5];
  |                                        ~~~~

warning: `single_range` (bin "single_range") generated 1 warning

I expected to see this happen:
No warnings produced.

Version

No response

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions