" is not implemented I cannot compile my simple Rust program: fn main() { let nums = [1, 2]; let noms =...">

The value "core :: ops :: Index <i32>" is not implemented

I cannot compile my simple Rust program:

fn main() {

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

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

I get this error while compiling:

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

If I do an explicit type conversion, it works, but I'm not sure if this is the right way:

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

What is the correct way to access array elements in this case?

Related discussions on GitHub, Reddit:

+4
source share
1 answer

You can use type annotations to make sure the numbers in your array are of the correct type:

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, , .

+3

All Articles