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