簡體   English   中英

在Rust中傳遞數組的數組(或切片的切片)

[英]Pass array of arrays (or slice of slices) 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;
}

問題是,似乎我必須為“內部”數組指定一個數組長度(在這里: LNGTH )。

因此,以下代碼可以正常工作:

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);    
} 

但是,如果我將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`.

從C的角度來看,我想有一個接受T**類型參數的函數。 C中的對應函數如下所示

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

這是切片的版本:

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);
}

您必須將形式參數更改為slice of slices,並且y_array的元素y_array必須是slices(后者基本上是錯誤消息所說的內容)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM