从向量中删除结构,同时可变地迭代它

问题描述 投票:0回答:1

相关代码:

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`.
rust iteration
1个回答
2
投票

您可以使用

retain_mut
方法来实现:

self.watermelons.retain_mut(|watermelon| {
    if watermelon.clr == Color::RED {
        self.score += 1;
        false
    } else {
        true
    }
});

顺便说一下,你问题中的代码实际上并没有改变向量的元素。如果您的真实代码也是这种情况,那么您可以使用

retain
而不是
retain_mut

© www.soinside.com 2019 - 2024. All rights reserved.