【问题标题】:Error[E0277]: the type `[u32]` cannot be indexed by `u32`错误[E0277]:类型“[u32]”不能被“u32”索引
【发布时间】:2021-03-23 11:44:49
【问题描述】:

我对下面的变量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>`

Playground

【问题讨论】:

    标签: rust slice vec


    【解决方案1】:

    IndexIndexMut 特征使索引成为可能。

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

    虽然,它强加了一个 trait bound,用于索引的类型应该实现 SliceIndex&lt;[T]&gt;

    impl<T, I> Index<I> for Vec<T>
    where
        I: SliceIndex<[T]>
    

    SliceIndex 是为 usize 实现的,因此可以使用类型 usize 作为索引。

    它不适用于u32,因此您不能使用u32 作为索引。

    i 的类型为u32,因为它是从0..number 范围内接收的,其中number 的类型为u32


    一个简单的解决方法是将i 转换为usize

    if a[i as usize] % 2 != 0
    

    只要您至少在32 位机上,就可以安全地完成此转换。

    根据definition of usize

    这个原语的大小是引用内存中任何位置需要多少字节


    此外,您的代码不需要您使用u32。相反,您应该从一开始就使用usize

    【讨论】:

      【解决方案2】:

      number 的类型更改为usize,因此for i in 0..number 的范围也将迭代usizes。索引通常使用usize

      【讨论】:

        【解决方案3】:

        快速备注:不要将number 的类型永远更改为usize 或不断将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);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-07-28
          • 2023-04-03
          • 2021-11-23
          • 2018-07-25
          • 2021-01-20
          • 1970-01-01
          • 2020-04-24
          • 2020-12-17
          相关资源
          最近更新 更多