Reputation: 26048
I have an array and vector and the vector is populated in a loop. In each iteration of the loop, I want to check whether the last 4 elements of the vector is equal to 4 elements of the array. The size of the array is 4.
Is there a better way to do that than comparing their elements one by one? I'd like something like my_array == my_vector[4, -4]
Upvotes: 11
Views: 10267
Reputation: 11197
Is there a better way to do that than comparing their elements one by one?
Yes, you can compare a slice of the array with a slice of the vector:
fn main() {
let a = [3, 4, 5, 6];
let v = vec![0, 1, 2, 3, 4, 5, 6];
assert_eq!(&a[..], &v[v.len() - 4..]);
}
A slice can be created with any range form. Here are some examples of creating slices:
fn main() {
let v = vec![0, 1, 2, 3, 4, 5, 6];
// indexes 0, 1, 2 (3 not included)
assert_eq!(&[0, 1, 2], &v[..3]);
// indexes 2, 3 (4 not included)
assert_eq!(&[2, 3], &v[2..4]);
// indexes 3, 4, ..until the last
assert_eq!(&[3, 4, 5, 6], &v[3..]);
// all indexes
assert_eq!(&[0, 1, 2, 3, 4, 5, 6], &v[..]);
}
Upvotes: 17