Slice equality?

I find most of my projects have something like this in them:

fn slice_eq<'a, T: PartialEq>(a: &'a [T], b: &'a [T]) -> bool {
    if a.len() != b.len() {
        return false;
    }

    for (i, val) in a.iter().enumerate() {
        if val != &b[i] {
            return false;
        }
    }

    true
}

Could Rust provide this in the standard library? There seem to be numerous posts out there about golfing and micro-optimizing this function.

Have you tried a == b?

7 Likes

lol, I guess this works now. Did it not used to work with slice references?

AFAICS, even Rust 1.0 had PartialEq<[B]> for [A] and for ?Sized references.

2 Likes

Yup, Rust 1.0 supports == for slices: Compiler Explorer

5 Likes

If you want to keep the function, it probably can be simplified to:

#[inline(always)]
fn slice_eq<'a, T: PartialEq>(a: &'a [T], b: &'a [T]) -> bool {
    a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| a == b)
}

This iterator does no bound checks on the arrays.

2 Likes

Which mirrors the default implementation for slices in the standard library. But std’s implementation also is able to use specialization to create an explicit call to memcmp for primitives types such as u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, usize, isize, char, bool. So probably the better simplification is to just write a == b even in a dedicated slice_eq function.

10 Likes