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]
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[..]);
}
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