Rust

Rust

Made by DeepSource

Needless iteration over collection that allows indexing RS-W1091

Performance
Major

Using .iter().nth(_) is a method of accessing the nth element of an iterable. However, some collections such as slices or VecDeques allow direct access to the nth element through helper methods such as get and get_mut (for mutable access). Not only are these methods more consise, they are also more performant.

The chains may be replaced as follows:

  • .iter().nth(idx) with .get(idx)
  • .iter_mut().nth(idx) with .get_mut(idx)

Bad practice

let v = vec![1, 2, 3];
assert_eq!(v.iter().nth(2), Some(&3));

Recommended

let v = vec![1, 2, 3];
assert_eq!(v.get(2), Some(&3));