11

我对i下面的变量做错了什么?为什么编译器说我不能Vec用 a索引 au32以及如何修复它?

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>`

操场

4

3 回答 3

8

IndexIndexMut特征使索引成为可能。

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

虽然,它强加了一个用于索引的类型应该实现的特征限制SliceIndex<[T]>

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

SliceIndex被实现,usize因为它可以使用类型usize作为索引。

它没有被实现u32,因此您不能u32用作索引。

i具有类型u32,因为它是从具有类型的范围接收0..number的。numberu32


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

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

只要您至少在一32台机器上,就可以安全地完成此演员阵容。

根据usize 的定义

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


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

于 2020-12-12T06:04:34.383 回答
2

快速评论:不要将类型更改numberusize永远或不断转换iusize一,可以使用以下构造,该构造numberusize用于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);
}
于 2021-06-23T07:29:31.317 回答
2

将类型更改numberusize,因此范围for i in 0..number也将在 s 上进行迭代usize。索引通常使用usize

于 2020-12-12T06:24:21.543 回答