#Vec<Mut<Component>> from query

9 messages · Page 1 of 1 (latest)

glad pivot
#

Is there any way to get a Vec<Mut<Component>> from a query and an entity list?
I have tried this:

let mut iter = q.iter_many_mut(q_entities.iter());
let mut vec = vec![];
while let Some(e) = iter.fetch_next() {
    vec.push(e);
}```
But I run into an error that `iter` cannot be mutably borrowed more than once at a time.
deep maple
#

Yeah in this specific case, there could be repeat entities in q_entities, so it refuses to let you collect them

#

Could you share what q and q_entities are? There might be a workaround

hardy pilot
#

you could simple use collect to get your query results into a vec

glad pivot
# deep maple Could you share what `q` and `q_entities` are? There might be a workaround

q is Query<&mut SomeComponent> and q_entities is Query<Entity, With<Selected>>. For now I have found the workaround of just using Query<&mut SomeComponent, With<Selected>>(which I can then collect into a Vec) but since I have quite a lot of different components which I need to query for this is going to end up in a mes svery quickly unless there's a better way of doing it!

deep maple
deep maple
short delta
deep maple
# short delta How does repeat entities happen?

I said this before Thomas explained q_entities was a query. In this case, there can't be any repeats. But the iter_many_mut method accepts arbitrary iterators as argument, which themselves could have repeat entities (for example, you can pass it &[entity, entity] as argument).

If it was possible to access several items of the output of iter_many_mut at a time, it would be possible to create several mutable references to the same component on the same entity, which is in violation of rust's soundness rules.

This is why iter_many_mut doesn't return an iterator, but a thing you can call fetch_next on. This forces having to drop the previous reference before creating a new one, hence preventing having two mutable references at the same time to the same component on the same entity. Sadly, this means that the same limit applies if the iterator passed as argument doesn't have any repeat.