使用常量(非文字)声明数组作为维度说明符

Jon*_*röm 0 arrays indexing declaration rust

下面的代码可以工作,但是为了方便地改变数组的大小和循环的索引范围,变量max可以用来指定数组的维数吗?

fn main() {
    let max: i64 = 3;

    let mut arr2: [[f64; 3]; 3] = [[0.0; 3]; 3]; //replace 3 by max?
    // let mut arr2: [[f64; max]; max] = [[0.0; max]; max]; //does not work

    let pi: f64 = 3.1415926535;
    let max2 = max as usize;

    for ii in 0..max2 {
        for jj in 0..max2 {
            let i = ii as f64;
            let j = jj as f64;
            arr2[ii][jj] = ((i + j) * pi * 41.0).sqrt().sin();
            println!("arr2[{}][{}] is {}", ii, jj, arr2[ii][jj]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用注释掉的行来声明我收到此错误:

error[E0513]: no type for local variable 10
 --> <anon>:6:32
  |
6 |     let mut arr2: [[f64; max]; max] = [[0.0; max]; max]; //does not work
  |                                ^^^
Run Code Online (Sandbox Code Playgroud)

Fra*_*gné 5

必须在编译时使用已知的固定大小声明Rust中的数组.

如果在编译时确实知道大小,那么定义一个常量而不是变量:

const MAX: usize = 3;
Run Code Online (Sandbox Code Playgroud)

如果在编译时未知大小,请使用Vec替代.