4
votes

I can't compile my elementary 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 that it's 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:

1

1 Answers

3
votes

You can use type annotations to make sure the numbers in your array have the right 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]);
    }
}

This way, your array contains numbers of type usize instead of i32s

In general, if you're not explicit about which type a numeric literal has, and if the type inference can't figure out what the type should be, it will default to i32, which might not be what you want.