Sending arrays of unknown length to functions

Hello having some troubles with arrays and functions. I want to have a function that can take arrays of variable length. Using the code below i get an error telling me: "mismatched types [E0308]:
expected type &[u8]
found type [u8; 5]
expected &[u8], found array of 5 elements"

Calling the function:

let data: [u8; 5] = [0x0a, 0x00, 0x00, 0x00, 0x00];
let mut retdata: [u8; 5];

spi1sendreceive(data, retdata, 5);

fn spi1sendreceive(data: &[u8], ret: &mut [u8], len: u8 )

Any pointers to how to solve this would be welcome.

You need to pass a reference, not the array itself:

spi1sendreceive(&data, &mut retdata, 5);
1 Like

This worked, wonders,thanks :slight_smile:

Hit another obstacle in the function though:

fn spi1sendreceive(data: &[u8], ret: &mut [u8], len: u8 )
let mut x = 0;
while x < len
ret = spi1() as u8;<--- this line
x = x + 1;

gives me:
the trait bound u8: core::slice::SliceIndex<u8> is not satisfied [E0277]:
slice indices are of type usize or ranges of usize
required because of the requirements on the impl of core::ops::Index<u8> for [u8]
the trait core::slice::SliceIndex<u8> is not implemented for u8

Edit: Solved it by casting ret to ret[x as usize], feels kinda hacky though

Since x is not given a specific type, and it's compared against a u8 value (len), the compiler infers that it should have the type u8 as well. However, any indexing for slices (ret[x]) must use the usize type, so this is a type error. You could work around this by making your index variable have the proper type and casting (either while x < len as usize, or ret[x as usize]), but more idiomatic code would look like this:

for x in ret {
    *x = spr1() as u8;

This avoids the need to pass in a length argument to the function entirely. You could also use ret.len() instead of passing in len, which would give you a usize value as well.