I have a 2D vector that rejects indexing using i32
values, but works if I cast those values using 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() {}
When I compile, I get the error message
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>>`
If I change the code to have
p[i as usize][j as usize].color = c.clone();
Then everything works fine. However, this feels like it would be a really bizarre choice with no reason not to be handled by the Vec
type.
In the documentation, there are plenty of examples like
assert_eq!(vec[0], 1);
By my understanding, if a plain number with no decimal is by default an i32
, then there's no reason using an i32
to index shouldn't work.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…