Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare a Vec with a Range in rust

Tags:

rust

I want to check if a Vec is equal to [0, 1, 2, ...]. I've tried various variants of:

vec == &(0..vec.len())

But none of them seem to work. Do I just have to write a loop out long-hand?

like image 664
Chris Jefferson Avatar asked Jan 28 '23 18:01

Chris Jefferson


1 Answers

You can use iterators to compare a Vec<T> (or more generally, a slice [T]) to a range (Playground):

let v = vec![0, 1, 2, 3, 4];

if v.iter().cloned().eq(0..v.len()) {
    println!("v contains 0..5");
} else {
    println!("v doesn't contain 0..5");
}

Let's dissect the important part:

v.iter().cloned().eq(0..v.len())
  • v.iter() creates an iterator over references to the elements in the vector (Iterator<Item = &{integer}>).
  • .cloned() clones each element in the iterator to go from reference to owned value. This is required because we cannot compare &{integer} to {integer}. Luckily, cloning a simple integer is basically free. So now we have Iterator<Item = {integer}>.
  • .eq is a method of Iterator which compares the iterator to another iterator.
  • 0..v.len() is an range from 0 (inclusive) to v.len() (exclusive). Such a range implements Iterator.
like image 83
Lukas Kalbertodt Avatar answered Feb 07 '23 19:02

Lukas Kalbertodt