Skip to content

Commit 900e339

Browse files
Add IntoIterator impls for &Query and &mut Query (#4692)
# Objective These types of IntoIterator impls are a common pattern in Rust, and these implementations make this common pattern work for bevy queries.
1 parent a2f966e commit 900e339

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

crates/bevy_ecs/src/system/mod.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -925,4 +925,19 @@ mod tests {
925925
assert!(entity.contains::<A>());
926926
assert!(entity.contains::<B>());
927927
}
928+
929+
#[test]
930+
fn into_iter_impl() {
931+
let mut world = World::new();
932+
world.spawn().insert(W(42u32));
933+
run_system(&mut world, |mut q: Query<&mut W<u32>>| {
934+
for mut a in &mut q {
935+
assert_eq!(a.0, 42);
936+
a.0 = 0;
937+
}
938+
for a in &q {
939+
assert_eq!(a.0, 0);
940+
}
941+
});
942+
}
928943
}

crates/bevy_ecs/src/system/query.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1129,6 +1129,24 @@ impl<'w, 's, Q: WorldQuery, F: WorldQuery> Query<'w, 's, Q, F> {
11291129
}
11301130
}
11311131

1132+
impl<'w, 's, Q: WorldQuery, F: WorldQuery> IntoIterator for &'w Query<'_, 's, Q, F> {
1133+
type Item = ROQueryItem<'w, Q>;
1134+
type IntoIter = QueryIter<'w, 's, Q, ROQueryFetch<'w, Q>, F>;
1135+
1136+
fn into_iter(self) -> Self::IntoIter {
1137+
self.iter()
1138+
}
1139+
}
1140+
1141+
impl<'w, Q: WorldQuery, F: WorldQuery> IntoIterator for &'w mut Query<'_, '_, Q, F> {
1142+
type Item = QueryItem<'w, Q>;
1143+
type IntoIter = QueryIter<'w, 'w, Q, QueryFetch<'w, Q>, F>;
1144+
1145+
fn into_iter(self) -> Self::IntoIter {
1146+
self.iter_mut()
1147+
}
1148+
}
1149+
11321150
/// An error that occurs when retrieving a specific [`Entity`]'s component from a [`Query`]
11331151
#[derive(Debug)]
11341152
pub enum QueryComponentError {

0 commit comments

Comments
 (0)