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?
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
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With