rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

Use slices or arrays instead of vecs lint

Open leonardo-m opened this issue 2 years ago • 0 comments

What it does

The lint suggests to replace an allocated vec![] with a slice. In test blocks I see lot of vecs that aren't necessary.

Lint Name

use_slice_or_array

Category

perf

Advantage

It's more efficient.

Drawbacks

None, I think.

Example

#![warn(clippy::all)]
#![warn(clippy::nursery)]
#![warn(clippy::pedantic)]

fn append(mut items: Vec<i32>, suffix: &[i32]) -> Vec<i32> {
    items.extend_from_slice(suffix);
    items
}

fn main() {
    assert_eq!(vec![1, 2, 3, 4], append(vec![1, 2], &[3, 4]));
}

Could be written as:

#![warn(clippy::all)]
#![warn(clippy::nursery)]
#![warn(clippy::pedantic)]

fn append(mut items: Vec<i32>, suffix: &[i32]) -> Vec<i32> {
    items.extend_from_slice(suffix);
    items
}

fn main() {
    assert_eq!(&[1, 2, 3, 4][..], append(vec![1, 2], &[3, 4]));
}

This lint should suggest to use slices or arrays instead of probably-heap-allocated vecs. But only for short literals. Past a certain length better not to fire this lint.

leonardo-m avatar Jul 29 '22 19:07 leonardo-m