rust-lang / rust-lang/rust-clippy
`single_range_in_vec_init` stronger than expected, when type is known
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Locate the implementation and tests for the single_range_in_vec_init lint; start by reading how it determines the vector element type and handles surrounding type context. Add regression coverage for the annotated and function-argument examples, then verify those cases no longer warn while the existing intended warnings remain.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 52/100