How can I == arrays of same type?

โš“ Rust    ๐Ÿ“… 2025-11-08    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 5      

surdeus

Why does the compiler not catch when two arrays have the same(-ish?) type? When I make it explicit, the compiler is happy. But when it comes through generics, even though I poke the compilerโ€™s nose on the fact they are the same, it no longer compiles.

How can I cast these array types when they are known to be the same at compile time?

I want to avoid going the alternate route, when itโ€™s not necesary!

fn ok() {
    const SIZE1: usize = 1;
    const SIZE2: usize = 1;
    let a: [u8; SIZE1] = [1];
    let b: [u8; SIZE2] = [1];
    a == b;
}

fn not_ok<const SIZE1: usize, const SIZE2: usize>(a: [u8; SIZE1], b: [u8; SIZE2]) {
    if SIZE1 == SIZE2 {
        a == b;
    } else {
        expensive_comparison(a, b);
    }
}

error[E0277]: can't compare `[u8; SIZE1]` with `[u8; SIZE2]`
  --> src/main.rs:53:11
   |
53 |         a == b;
   |           ^^ no implementation for `[u8; SIZE1] == [u8; SIZE2]`
   |
   = help: the trait `PartialEq<[u8; SIZE2]>` is not implemented for `[u8; SIZE1]`

7 posts - 5 participants

Read full topic

๐Ÿท๏ธ Rust_feed