How can I define a slice of slices?

This code:

let test = [ 
    &[1, 2, 3], 
    &[10, 20]
];

Gives the following error on the [10, 20] array:

expected an array with a fixed size of 3 elements, found one with 2 elements

But I'm putting & characters before the inner arrays, so their type should be &[i32] for both, instead of [i32; 3] and [i32; 2]. Why is it not working?

1 Like

I believe it’s creating &[T; N]s, not &[T]. Try adding [..] to the end of both.

3 Likes

As @steveklabnik mentioned, type inference thinks you want an array of references to a 3-arity arrays, as that’s the first element it sees in there.

You can add [..] to just the first element (note it’s two periods, not 3, for the full range specifier) to tell inference you want slices. Or you can add a type ascription to the let binding: let test: [&[_]; 2] = ...

1 Like

Thank you! That was it.

Hi, what about this case?

let hash_and_nonce: [&[_]; 2]  = [
    &header.hash().unwrap(), // 32 bytes
    &nonce.to_le_bytes() // 8 bytes
];

But I need also have a .concat() at the end of slice. Can't inline it?

Found solution:

let hash_and_nonce = ([
    &header.hash().unwrap(),
    &nonce.to_le_bytes(),
] as [&[_]; 2]).concat();

Please don't revive old threads to ask new questions. Create a new thread.