gpt4 book ai didi

rust - 错误[E0277] : the type `[u32]` cannot be indexed by `u32`

转载 作者:行者123 更新时间:2023-12-03 11:24:21 27 4
gpt4 key购买 nike

我对变量 i 做错了什么?以下?为什么编译器说我不能索引 Vecu32我该如何解决?

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

最佳答案

Index 使索引成为可能和 IndexMut性状。
您正在使用 Vec 并实现 Index IndexMut 性状。
虽然,它强加了一个 trait bound,用于索引的类型应该实现 SliceIndex<[T]> :

impl<T, I> Index<I> for Vec<T>
where
I: SliceIndex<[T]>
SliceIndex usize 实现因此可以使用类型 usize作为索引。
它不是为 u32 实现的因此你不能使用 u32作为索引。 i有一个类型 u32因为它是从范围 0..number 接收的哪里 number有类型 u32 .

一个简单的解决方法是转换 iusize :
if a[i as usize] % 2 != 0
只要您至少在 32 上,就可以安全地完成此转换。位机。
根据 definition of usize :

The size of this primitive is how many bytes it takes to reference any location in memory



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

关于rust - 错误[E0277] : the type `[u32]` cannot be indexed by `u32` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65261859/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com