繁体   English   中英

错误[E0277]:类型“[u32]”不能被“u32”索引

[英]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>`

操场

IndexIndexMut特征使索引成为可能。

您正在使用Vec并且它实现了IndexIndexMut特征。

虽然,它强加了用于索引的类型应该实现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完成

快速备注: usizenumber的类型更改为永远使用或不断将i转换为使用usize ,不如使用以下构造,该构造仅将number usizefor循环:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM