特性`core::ops::Index<i32>` 未实现

Trait `core::ops::Index<i32>` is not implemented

我无法编译我的基本 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/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]);

如果我进行显式类型转换,它会起作用,但我不确定 这是正确的方法:

println!("{} says hello", noms[num-1 as usize]);

在这种情况下访问数组元素的正确方法是什么?

相关讨论 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 类型的数字,而不是 i32s

一般来说,如果你没有明确说明数字文字的类型,并且如果类型推断无法确定类型应该是什么,它将默认为 i32,这可能不是你想要的。