Compilation Trait`core::ops::Index<;i32>;`没有实施

Compilation Trait`core::ops::Index<;i32>;`没有实施,compilation,compiler-errors,rust,Compilation,Compiler Errors,Rust,我无法编译我的基本生锈程序: fn main() { let nums = [1, 2]; let noms = [ "Sergey", "Dmitriy", "Ivan" ]; for num in nums.iter() { println!("{} says hello", noms[num-1]); } } 我在编译时遇到此错误: Compiling hello_world v0.0.1 (file:///home/igor/r

我无法编译我的基本生锈程序:

fn main() {

    let nums = [1, 2];
    let noms = [ "Sergey", "Dmitriy", "Ivan" ];

    for num in nums.iter() {
        println!("{} says hello", noms[num-1]);
    }
}
我在编译时遇到此错误:

   Compiling hello_world v0.0.1 (file:///home/igor/rust/projects/hello_world)
src/main.rs:23:61: 23:72 error: the trait `core::ops::Index<i32>` is not implemented for the type `[&str]` [E0277]
src/main.rs:23         println!("{} says hello", noms[num-1]);
在这种情况下,访问数组元素的正确方法是什么

关于GitHub、Reddit的相关讨论:


您可以使用类型注释来确保数组中的数字具有正确的类型:

fn main() {

    let nums = [1us, 2]; // note the us suffix
    let noms = [ "Sergey", "Dmitriy", "Ivan" ];

    for num in nums.iter() {
        println!("{} says hello", noms[num-1]);
    }
}
这样,您的数组包含类型为
usize
的数字,而不是
i32
s的数字

通常,如果您不清楚数值文字的类型,并且类型推断无法确定该类型应该是什么,那么它将默认为
i32
,这可能不是您想要的

fn main() {

    let nums = [1us, 2]; // note the us suffix
    let noms = [ "Sergey", "Dmitriy", "Ivan" ];

    for num in nums.iter() {
        println!("{} says hello", noms[num-1]);
    }
}