【发布时间】:2018-05-30 04:24:01
【问题描述】:
我有一个 2D 向量拒绝使用 i32 值进行索引,但如果我使用 as usize 转换这些值,则可以:
#[derive(Clone)]
struct Color;
struct Pixel {
color: Color,
}
fn shooting_star(p: &mut Vec<Vec<Pixel>>, x: i32, y: i32, w: i32, h: i32, c: Color) {
for i in x..=w {
for j in y..=h {
p[i][j].color = c.clone();
}
}
}
fn main() {}
当我编译时,我收到错误消息
error[E0277]: the trait bound `i32: std::slice::SliceIndex<[std::vec::Vec<Pixel>]>` is not satisfied
--> src/main.rs:11:13
|
11 | p[i][j].color = c.clone();
| ^^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `std::slice::SliceIndex<[std::vec::Vec<Pixel>]>` is not implemented for `i32`
= note: required because of the requirements on the impl of `std::ops::Index<i32>` for `std::vec::Vec<std::vec::Vec<Pixel>>`
如果我将代码更改为具有
p[i as usize][j as usize].color = c.clone();
然后一切正常。然而,感觉这将是一个非常奇怪的选择,没有理由不被 Vec 类型处理。
在documentation,有很多这样的例子
assert_eq!(vec[0], 1);
据我了解,如果默认情况下没有小数的纯数字是 i32,那么使用 i32 来索引没有理由不应该工作。
【问题讨论】:
标签: rust