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;
}
fn swap_array<T>(x: &mut [&[T; LNGTH]])" — that's what it already is. Did you mean to sayfn swap_array<T>(x: &mut [&[T]])?int x[5][10]is not convertible toint**but toint (*)[10].