Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to concat arrays with differend fixed sizes?

I’m trying Rust and unfortunately I’m already stuck with small tasks like concating u8 arrays.

I am trying to join the following arrays:

let arrayOne: &[u8; 500] = &[0; 500];
let arrayTwo: &[u8; 100] = &[1; 100];
let arrayThree: &[u8] = &[1, 2, 3];

let mergedArray = [arrayOne, arrayTwo, arrayThree].concat();

but im getting the error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

mismatched types
expected an array with a fixed size of 500 elements, found one with 100 elementsrustcClick for full compiler diagnostic
let arrayTwo: &[u8; 100] // size = 8, align = 0x8

I don’t quite understand why this is not allowed and how it is otherwise done.

Especially since the following code seems to be ok:

let arrayOne: &[u8; 500] = &[0; 500];
let arrayThree: &[u8] = &[1, 2, 3];

let mergedArray = [arrayOne, arrayThree].concat();

>Solution :

The problem with the first example is that once the compiler looks at the second item it tries to coerce the &[u8; 500] to a &[u8; 100] and vice versa, neither of which are allowed coercions. It doesn’t see that both could be coerced to the same &[u8] because that would require checking all possible coercion targets every time wich would have a massive performance impact on compilation.

The second example works because once the type of the second element &[u8] is encounterd it sees it can coerce &[u8; 500] to a slice, too and is able to continue.

You can cast the first array reference to a slice to help the compiler figure out that everything should be coerced to slices:

fn main() {
    let array_one: &[u8; 500] = &[0; 500];
    let array_two: &[u8; 100] = &[0; 100];
    let array_three: &[u8] = &[1, 2, 3];

    let merged_array = [array_one as &[_], array_two, array_three].concat();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading