简体   繁体   中英

Pass array of arrays (or slice of slices) in Rust

I need to pass a reference to an array of references to arrays (or slice of slices) to the following function in Rust

const LNGTH: usize = 5;

fn swap_array<T>(x: &mut [&[T; LNGTH]]) {
    let temp = x[1];
    x[1] = x[0];
    x[0] = temp;
}

The problem is that it seems I have to specify an array length for the "inner" arrays (here: LNGTH ).

So, the following code works fine:

fn main() {
    let x_array: [i32; LNGTH] = [5,2,8,9,1];
    let x_other: [i32; LNGTH] = [6,7,6,7,6];        
    let mut y_array: [&[i32; LNGTH]; 2] = [&x_array, &x_other];
    println!("before : {:?}", y_array);
    swap_array(&mut y_array);
    println!("after  : {:?}", y_array);    
} 

But if I change the signature of swap_array to fn swap_array<T>(x: &mut [&[T]]) , I get the following error:

error[E0308]: mismatched types
  --> src/main.rs:14:16
   |
14 |     swap_array(&mut y_array[..]);
   |                ^^^^^^^^^^^^^^^^ expected slice, found array of 5 elements
   |
   = note: expected type `&mut [&[_]]`
              found type `&mut [&[i32; 5]]`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: Could not compile `tut_arrays`.

From the perspective of C, I would like to have a function that accepts arguments of type T** . A corresponding function in C would look like that

void swap_arrays(my_type ** x) {
    my_type* temp = x[1];
    x[1] = x[0];
    x[0] = temp;
}

Here is a slice-of-slices version:

const LEN: usize = 5;

fn swap_array<T>(x: &mut [&[T]]) {
    let temp = x[1];
    x[1] = x[0];
    x[0] = temp;
}

fn main() {
    let x_array: [i32; LEN] = [5, 2, 8, 9, 1];
    let x_other: [i32; LEN] = [6, 7, 6, 7, 6];
    let mut y_array: [&[i32]; 2] = [&x_array, &x_other];
    println!("before : {:?}", y_array);
    swap_array(&mut y_array);
    println!("after  : {:?}", y_array);
}

You have to change the formal argument to slice of slices, and the elements of y_array must be slices, too (the latter is basically what the error message said).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM