相关代码:
for watermelon in self.watermelons.iter_mut() {
if watermelon.clr == Color::RED {
self.score += 1;
self.watermelons.remove(*self.watermelons.index(watermelon));
}
}
pub struct Watermelon {
pub pos: (f32, f32),
pub size: (i32, i32),
speed: f64,
pub clr: Color
}
我收到此错误:
error[E0277]: the type `[Watermelon]` cannot be indexed by `&mut Watermelon`
--> src/game.rs:46:53
|
46 | ...lf.watermelons.index(watermelon));
| ----- ^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
| |
| required by a bound introduced by this call
|
= help: the trait `SliceIndex<[Watermelon]>` is not implemented for `&mut Watermelon`, which is required by `Vec<Watermelon>: Index<_>`
= note: required for `Vec<Watermelon>` to implement `Index<&mut Watermelon>`
For more information about this error, try `rustc --explain E0277`.
retain_mut
方法来实现:
self.watermelons.retain_mut(|watermelon| {
if watermelon.clr == Color::RED {
self.score += 1;
false
} else {
true
}
});
顺便说一下,你问题中的代码实际上并没有改变向量的元素。如果您的真实代码也是这种情况,那么您可以使用
retain
而不是 retain_mut
。