rust-clippy/tests/ui/repeat_vec_with_capacity.fixed
Robert Spencer acc3842d43 Add new map_with_unused_argument_over_ranges lint
This lint checks for code that looks like
```rust
  let something : Vec<_> = (0..100).map(|_| {
    1 + 2 + 3
  }).collect();
```
which is more clear as
```rust
  let something : Vec<_> = std::iter::repeat_with(|| {
    1 + 2 + 3
  }).take(100).collect();
```
or
```rust
  let something : Vec<_> =
      std::iter::repeat_n(1 + 2 + 3, 100)
      .collect();
```

That is, a map over a range which does nothing with the parameter
passed to it is simply a function (or closure) being called `n`
times and could be more semantically expressed using `take`.
2024-10-29 21:32:00 +00:00

39 lines
1.1 KiB
Rust

#![allow(clippy::map_with_unused_argument_over_ranges)]
#![warn(clippy::repeat_vec_with_capacity)]
fn main() {
{
(0..123).map(|_| Vec::<()>::with_capacity(42)).collect::<Vec<_>>();
//~^ ERROR: repeating `Vec::with_capacity` using `vec![x; n]`, which does not retain capacity
}
{
let n = 123;
(0..n).map(|_| Vec::<()>::with_capacity(42)).collect::<Vec<_>>();
//~^ ERROR: repeating `Vec::with_capacity` using `vec![x; n]`, which does not retain capacity
}
{
macro_rules! from_macro {
($x:expr) => {
vec![$x; 123];
};
}
// vec expansion is from another macro, don't lint
from_macro!(Vec::<()>::with_capacity(42));
}
{
std::iter::repeat_with(|| Vec::<()>::with_capacity(42));
//~^ ERROR: repeating `Vec::with_capacity` using `iter::repeat`, which does not retain capacity
}
{
macro_rules! from_macro {
($x:expr) => {
std::iter::repeat($x)
};
}
from_macro!(Vec::<()>::with_capacity(42));
}
}