[英]Error[E0277]: the type `[u32]` cannot be indexed by `u32`
我对下面的变量i
做错了什么? 为什么编译器说我不能用u32
索引Vec
,我该如何解决?
fn main() {
let a: Vec<u32> = vec![1, 2, 3, 4];
let number: u32 = 4;
let mut count = 0;
for i in 0..number {
if a[i] % 2 != 0 {
count += 1;
} else {
continue;
}
}
println!("{}", count);
}
错误:
error[E0277]: the type `[u32]` cannot be indexed by `u32`
--> src/main.rs:7:12
|
7 | if a[i] % 2 != 0 {
| ^^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `SliceIndex<[u32]>` is not implemented for `u32`
= note: required because of the requirements on the impl of `Index<u32>` for `Vec<u32>`
您正在使用Vec
并且它实现了Index
和IndexMut
特征。
虽然,它强加了用于索引的类型应该实现SliceIndex<[T]>
的特征限制:
impl<T, I> Index<I> for Vec<T>
where
I: SliceIndex<[T]>
SliceIndex
是为usize
实现的,因此可以使用usize
类型作为索引。
它不适用于u32
,因此您不能使用u32
作为索引。
i
具有 u32 类型,因为它是从u32
范围内接收的,其中number
具有0..number
u32
。
一个简单的解决方法是将i
转换为usize
:
if a[i as usize] % 2 != 0
只要您在至少32
位机器上,就可以安全地完成此转换。
根据usize 的定义:
此原语的大小是引用 memory 中的任何位置所需的字节数
此外,您的代码不需要您使用u32
。 相反,您应该从一开始就使用usize
。
将number
的类型更改为usize
,因此 0..number for i in 0..number
的范围也将遍历usize
s。 索引通常使用usize
完成
快速备注: usize
将number
的类型更改为永远使用或不断将i
转换为使用usize
,不如使用以下构造,该构造仅将number
usize
为for
循环:
fn main() {
let a: Vec<u32> = vec![1, 2, 3, 4];
let number: u32 = 4;
let mut count = 0;
for i in 0..number as usize {
if a[i] % 2 != 0 {
count += 1;
} else {
continue;
}
}
println!("{}", count);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.