简体   繁体   English

在Rust中传递数组的数组(或切片的切片)

[英]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 我需要将对数组的引用的数组的引用传递给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 ). 问题是,似乎我必须为“内部”数组指定一个数组长度(在这里: 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: 但是,如果我将swap_array的签名swap_arrayfn swap_array<T>(x: &mut [&[T]])fn swap_array<T>(x: &mut [&[T]])出现以下错误:

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** . 从C的角度来看,我想有一个接受T**类型参数的函数。 A corresponding function in C would look like that C中的对应函数如下所示

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). 您必须将形式参数更改为slice of slices,并且y_array的元素y_array必须是slices(后者基本上是错误消息所说的内容)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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