pub struct QueryState<D, F = ()>where
D: QueryData,
F: QueryFilter,{ /* private fields */ }Expand description
Provides scoped access to a World state according to a given QueryData and QueryFilter.
This data is cached between system runs, and is used to:
- store metadata about which
TableorArchetypeare matched by the query. “Matched” means that the query will iterate over the data in the matched table/archetype. - cache the
Stateneeded to compute theFetchstruct used to retrieve data from a specificTableorArchetype - build iterators that can iterate over the query results
§Safety
If the query is not read-only,
then before calling any other methods on a new QueryState
other than QueryState::update_archetypes, QueryState::update_archetypes_unsafe_world_cell,
Self::init_access must be called.
Implementations§
Source§impl<D, F> QueryState<D, F>where
D: QueryData,
F: QueryFilter,
impl<D, F> QueryState<D, F>where
D: QueryData,
F: QueryFilter,
Sourcepub fn as_readonly(&self) -> &QueryState<<D as QueryData>::ReadOnly, F>
pub fn as_readonly(&self) -> &QueryState<<D as QueryData>::ReadOnly, F>
Converts this QueryState reference to a QueryState that does not access anything mutably.
Sourcepub fn component_access(&self) -> &FilteredAccess
pub fn component_access(&self) -> &FilteredAccess
Returns the components accessed by this query.
Sourcepub fn matched_tables(&self) -> impl Iterator<Item = TableId>
pub fn matched_tables(&self) -> impl Iterator<Item = TableId>
Returns the tables matched by this query.
Sourcepub fn matched_archetypes(&self) -> impl Iterator<Item = ArchetypeId>
pub fn matched_archetypes(&self) -> impl Iterator<Item = ArchetypeId>
Returns the archetypes matched by this query.
Sourcepub unsafe fn new_unchecked(world: &mut World) -> QueryState<D, F>
pub unsafe fn new_unchecked(world: &mut World) -> QueryState<D, F>
Creates a new QueryState from a given World and inherits the result of world.id().
Unlike QueryState::new, this does not check access of nested queries,
so Self::init_access must be called before querying using this state or returning it to safe code.
§Safety
If the query is not read-only,
then before calling any other methods on the returned QueryState
other than QueryState::update_archetypes, QueryState::update_archetypes_unsafe_world_cell,
Self::init_access must be called.
Sourcepub fn init_access(
&self,
system_name: Option<&str>,
component_access_set: &mut FilteredAccessSet,
world: UnsafeWorldCell<'_>,
)
pub fn init_access( &self, system_name: Option<&str>, component_access_set: &mut FilteredAccessSet, world: UnsafeWorldCell<'_>, )
Adds all access from this query and any nested queries to the component_access_set.
Panics if the access from this query and any nested queries conflict with each other
or with any previous access.
Sourcepub fn new(world: &mut World) -> QueryState<D, F>
pub fn new(world: &mut World) -> QueryState<D, F>
Creates a new QueryState from a given World and inherits the result of world.id().
Sourcepub fn try_new(world: &World) -> Option<QueryState<D, F>>
pub fn try_new(world: &World) -> Option<QueryState<D, F>>
Creates a new QueryState from an immutable World reference and inherits the result of world.id().
This function may fail if, for example, the components that make up this query have not been registered into the world.
Sourcepub fn from_builder(builder: &mut QueryBuilder<'_, D, F>) -> QueryState<D, F>
pub fn from_builder(builder: &mut QueryBuilder<'_, D, F>) -> QueryState<D, F>
Creates a new QueryState from a given QueryBuilder and inherits its FilteredAccess.
Sourcepub fn query<'w, 's>(
&'s mut self,
world: &'w World,
) -> Query<'w, 's, <D as QueryData>::ReadOnly, F>
pub fn query<'w, 's>( &'s mut self, world: &'w World, ) -> Query<'w, 's, <D as QueryData>::ReadOnly, F>
Creates a Query from the given QueryState and World.
This will create read-only queries, see Self::query_mut for mutable queries.
Sourcepub fn query_manual<'w, 's>(
&'s self,
world: &'w World,
) -> Query<'w, 's, <D as QueryData>::ReadOnly, F>
pub fn query_manual<'w, 's>( &'s self, world: &'w World, ) -> Query<'w, 's, <D as QueryData>::ReadOnly, F>
Creates a Query from the given QueryState and World.
This method is slightly more efficient than QueryState::query in some situations, since
it does not update this instance’s internal cache. The resulting query may skip an entity that
belongs to an archetype that has not been cached.
To ensure that the cache is up to date, call QueryState::update_archetypes before this method.
The cache is also updated in QueryState::new, QueryState::get, or any method with mutable
access to self.
This will create read-only queries, see Self::query_mut for mutable queries.
Sourcepub fn query_mut<'w, 's>(
&'s mut self,
world: impl Into<DeferredWorld<'w>>,
) -> Query<'w, 's, D, F>
pub fn query_mut<'w, 's>( &'s mut self, world: impl Into<DeferredWorld<'w>>, ) -> Query<'w, 's, D, F>
Creates a Query from the given QueryState and World.
Sourcepub unsafe fn query_unchecked<'w, 's>(
&'s mut self,
world: UnsafeWorldCell<'w>,
) -> Query<'w, 's, D, F>
pub unsafe fn query_unchecked<'w, 's>( &'s mut self, world: UnsafeWorldCell<'w>, ) -> Query<'w, 's, D, F>
Creates a Query from the given QueryState and World.
§Safety
This does not check for mutable query correctness. To be safe, make sure mutable queries have unique access to the components they query.
Sourcepub unsafe fn query_unchecked_manual<'w, 's>(
&'s self,
world: UnsafeWorldCell<'w>,
) -> Query<'w, 's, D, F>
pub unsafe fn query_unchecked_manual<'w, 's>( &'s self, world: UnsafeWorldCell<'w>, ) -> Query<'w, 's, D, F>
Creates a Query from the given QueryState and World.
This method is slightly more efficient than QueryState::query_unchecked in some situations, since
it does not update this instance’s internal cache. The resulting query may skip an entity that
belongs to an archetype that has not been cached.
To ensure that the cache is up to date, call QueryState::update_archetypes before this method.
The cache is also updated in QueryState::new, QueryState::get, or any method with mutable
access to self.
§Safety
This does not check for mutable query correctness. To be safe, make sure mutable queries
have unique access to the components they query.
This does not validate that world.id() matches self.world_id. Calling this on a world
with a mismatched WorldId is unsound.
Sourcepub unsafe fn query_unchecked_with_ticks<'w, 's>(
&'s mut self,
world: UnsafeWorldCell<'w>,
last_run: Tick,
this_run: Tick,
) -> Query<'w, 's, D, F>
pub unsafe fn query_unchecked_with_ticks<'w, 's>( &'s mut self, world: UnsafeWorldCell<'w>, last_run: Tick, this_run: Tick, ) -> Query<'w, 's, D, F>
Creates a Query from the given QueryState and World.
§Safety
This does not check for mutable query correctness. To be safe, make sure mutable queries have unique access to the components they query.
Sourcepub unsafe fn query_unchecked_manual_with_ticks<'w, 's>(
&'s self,
world: UnsafeWorldCell<'w>,
last_run: Tick,
this_run: Tick,
) -> Query<'w, 's, D, F>
pub unsafe fn query_unchecked_manual_with_ticks<'w, 's>( &'s self, world: UnsafeWorldCell<'w>, last_run: Tick, this_run: Tick, ) -> Query<'w, 's, D, F>
Creates a Query from the given QueryState and World.
This method is slightly more efficient than QueryState::query_unchecked_with_ticks in some situations, since
it does not update this instance’s internal cache. The resulting query may skip an entity that
belongs to an archetype that has not been cached.
To ensure that the cache is up to date, call QueryState::update_archetypes before this method.
The cache is also updated in QueryState::new, QueryState::get, or any method with mutable
access to self.
§Safety
This does not check for mutable query correctness. To be safe, make sure mutable queries
have unique access to the components they query.
This does not validate that world.id() matches self.world_id. Calling this on a world
with a mismatched WorldId is unsound.
Sourcepub fn is_empty(&self, world: &World, last_run: Tick, this_run: Tick) -> bool
pub fn is_empty(&self, world: &World, last_run: Tick, this_run: Tick) -> bool
Checks if the query is empty for the given World, where the last change and current tick are given.
This is equivalent to self.iter().next().is_none(), and thus the worst case runtime will be O(n)
where n is the number of potential matches. This can be notably expensive for queries that rely
on non-archetypal filters such as Added, Changed or Spawned which must individually check
each query result for a match.
§Panics
If world does not match the one used to call QueryState::new for this instance.
Sourcepub fn contains(
&self,
entity: Entity,
world: &World,
last_run: Tick,
this_run: Tick,
) -> bool
pub fn contains( &self, entity: Entity, world: &World, last_run: Tick, this_run: Tick, ) -> bool
Returns true if the given Entity matches the query.
This is always guaranteed to run in O(1) time.
Sourcepub fn update_archetypes(&mut self, world: &World)
pub fn update_archetypes(&mut self, world: &World)
Updates the state’s internal view of the World’s archetypes. If this is not called before querying data,
the results may not accurately reflect what is in the world.
This is only required if a manual method (such as Self::get_manual) is being called, and it only needs to
be called if the world has been structurally mutated (i.e. added/removed a component or resource). Users using
non-manual methods such as QueryState::get do not need to call this as it will be automatically called for them.
If you have an UnsafeWorldCell instead of &World, consider using QueryState::update_archetypes_unsafe_world_cell.
§Panics
If world does not match the one used to call QueryState::new for this instance.
Sourcepub fn update_archetypes_unsafe_world_cell(
&mut self,
world: UnsafeWorldCell<'_>,
)
pub fn update_archetypes_unsafe_world_cell( &mut self, world: UnsafeWorldCell<'_>, )
Updates the state’s internal view of the world’s archetypes. If this is not called before querying data,
the results may not accurately reflect what is in the world.
This is only required if a manual method (such as Self::get_manual) is being called, and it only needs to
be called if the world has been structurally mutated (i.e. added/removed a component or resource). Users using
non-manual methods such as QueryState::get do not need to call this as it will be automatically called for them.
§Note
This method only accesses world metadata.
§Panics
If world does not match the one used to call QueryState::new for this instance.
Sourcepub fn validate_world(&self, world_id: WorldId)
pub fn validate_world(&self, world_id: WorldId)
Sourcepub unsafe fn new_archetype(&mut self, archetype: &Archetype)
pub unsafe fn new_archetype(&mut self, archetype: &Archetype)
Update the current QueryState with information from the provided Archetype
(if applicable, i.e. if the archetype has any intersecting ComponentId with the current QueryState).
§Safety
archetype must be from the World this state was initialized from.
Sourcepub fn matches_component_set(
&self,
set_contains_id: &impl Fn(ComponentId) -> bool,
) -> bool
pub fn matches_component_set( &self, set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool
Returns true if this query matches a set of components. Otherwise, returns false.
Sourcepub fn transmute<'a, NewD>(
&self,
world: impl Into<UnsafeWorldCell<'a>>,
) -> QueryState<NewD>where
NewD: SingleEntityQueryData,
pub fn transmute<'a, NewD>(
&self,
world: impl Into<UnsafeWorldCell<'a>>,
) -> QueryState<NewD>where
NewD: SingleEntityQueryData,
Use this to transform a QueryState into a more generic QueryState.
This can be useful for passing to another function that might take the more general form.
See Query::transmute_lens for more details.
You should not call update_archetypes on the returned QueryState as the result will be unpredictable.
You might end up with a mix of archetypes that only matched the original query + archetypes that only match
the new QueryState. Most of the safe methods on QueryState call QueryState::update_archetypes internally, so this
best used through a Query
Sourcepub fn transmute_filtered<'a, NewD, NewF>(
&self,
world: impl Into<UnsafeWorldCell<'a>>,
) -> QueryState<NewD, NewF>where
NewD: SingleEntityQueryData,
NewF: QueryFilter,
pub fn transmute_filtered<'a, NewD, NewF>(
&self,
world: impl Into<UnsafeWorldCell<'a>>,
) -> QueryState<NewD, NewF>where
NewD: SingleEntityQueryData,
NewF: QueryFilter,
Creates a new QueryState with the same underlying FilteredAccess, matched tables and archetypes
as self but with a new type signature.
Panics if NewD or NewF require accesses that this query does not have.
Sourcepub fn join<'a, OtherD, NewD>(
&self,
world: impl Into<UnsafeWorldCell<'a>>,
other: &QueryState<OtherD>,
) -> QueryState<NewD>where
OtherD: QueryData,
NewD: SingleEntityQueryData,
pub fn join<'a, OtherD, NewD>(
&self,
world: impl Into<UnsafeWorldCell<'a>>,
other: &QueryState<OtherD>,
) -> QueryState<NewD>where
OtherD: QueryData,
NewD: SingleEntityQueryData,
Use this to combine two queries. The data accessed will be the intersection of archetypes included in both queries. This can be useful for accessing a subset of the entities between two queries.
You should not call update_archetypes on the returned QueryState as the result
could be unpredictable. You might end up with a mix of archetypes that only matched
the original query + archetypes that only match the new QueryState. Most of the
safe methods on QueryState call QueryState::update_archetypes internally, so
this is best used through a Query.
§Performance
This will have similar performance as constructing a new QueryState since much of internal state
needs to be reconstructed. But it will be a little faster as it only needs to compare the intersection
of matching archetypes rather than iterating over all archetypes.
§Panics
Will panic if NewD contains accesses not in Q or OtherQ.
Sourcepub fn join_filtered<'a, OtherD, OtherF, NewD, NewF>(
&self,
world: impl Into<UnsafeWorldCell<'a>>,
other: &QueryState<OtherD, OtherF>,
) -> QueryState<NewD, NewF>
pub fn join_filtered<'a, OtherD, OtherF, NewD, NewF>( &self, world: impl Into<UnsafeWorldCell<'a>>, other: &QueryState<OtherD, OtherF>, ) -> QueryState<NewD, NewF>
Use this to combine two queries. The data accessed will be the intersection of archetypes included in both queries.
§Panics
Will panic if NewD or NewF requires accesses not in Q or OtherQ.
Sourcepub fn get<'w>(
&mut self,
world: &'w World,
entity: Entity,
) -> Result<<<D as QueryData>::ReadOnly as QueryData>::Item<'w, '_>, QueryEntityError>
pub fn get<'w>( &mut self, world: &'w World, entity: Entity, ) -> Result<<<D as QueryData>::ReadOnly as QueryData>::Item<'w, '_>, QueryEntityError>
Gets the query result for the given World and Entity.
This can only be called for read-only queries, see Self::get_mut for write-queries.
If you need to get multiple items at once but get borrowing errors,
consider using Self::update_archetypes followed by multiple Self::get_manual calls,
or making a single call with Self::get_many or Self::iter_many.
This is always guaranteed to run in O(1) time.
Sourcepub fn get_many<'w, const N: usize>(
&mut self,
world: &'w World,
entities: [Entity; N],
) -> Result<[<<D as QueryData>::ReadOnly as QueryData>::Item<'w, '_>; N], QueryEntityError>
pub fn get_many<'w, const N: usize>( &mut self, world: &'w World, entities: [Entity; N], ) -> Result<[<<D as QueryData>::ReadOnly as QueryData>::Item<'w, '_>; N], QueryEntityError>
Returns the read-only query results for the given array of Entity.
In case of a nonexisting entity or mismatched component, a QueryEntityError is
returned instead.
Note that the unlike QueryState::get_many_mut, the entities passed in do not need to be unique.
§Examples
use bevy_ecs::prelude::*;
use bevy_ecs::query::QueryEntityError;
#[derive(Component, PartialEq, Debug)]
struct A(usize);
let mut world = World::new();
let entity_vec: Vec<Entity> = (0..3).map(|i|world.spawn(A(i)).id()).collect();
let entities: [Entity; 3] = entity_vec.try_into().unwrap();
world.spawn(A(73));
let mut query_state = world.query::<&A>();
let component_values = query_state.get_many(&world, entities).unwrap();
assert_eq!(component_values, [&A(0), &A(1), &A(2)]);
let wrong_entity = Entity::from_raw_u32(365).unwrap();
assert_eq!(match query_state.get_many(&mut world, [wrong_entity]).unwrap_err() {QueryEntityError::NotSpawned(error) => error.entity(), _ => panic!()}, wrong_entity);Sourcepub fn get_many_unique<'w, const N: usize>(
&mut self,
world: &'w World,
entities: UniqueEntityEquivalentArray<Entity, N>,
) -> Result<[<<D as QueryData>::ReadOnly as QueryData>::Item<'w, '_>; N], QueryEntityError>
pub fn get_many_unique<'w, const N: usize>( &mut self, world: &'w World, entities: UniqueEntityEquivalentArray<Entity, N>, ) -> Result<[<<D as QueryData>::ReadOnly as QueryData>::Item<'w, '_>; N], QueryEntityError>
Returns the read-only query results for the given UniqueEntityArray.
In case of a nonexisting entity or mismatched component, a QueryEntityError is
returned instead.
§Examples
use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};
#[derive(Component, PartialEq, Debug)]
struct A(usize);
let mut world = World::new();
let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();
let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();
world.spawn(A(73));
let mut query_state = world.query::<&A>();
let component_values = query_state.get_many_unique(&world, entity_set).unwrap();
assert_eq!(component_values, [&A(0), &A(1), &A(2)]);
let wrong_entity = Entity::from_raw_u32(365).unwrap();
assert_eq!(match query_state.get_many_unique(&mut world, UniqueEntityArray::from([wrong_entity])).unwrap_err() {QueryEntityError::NotSpawned(error) => error.entity(), _ => panic!()}, wrong_entity);Sourcepub fn get_mut<'w>(
&mut self,
world: &'w mut World,
entity: Entity,
) -> Result<<D as QueryData>::Item<'w, '_>, QueryEntityError>
pub fn get_mut<'w>( &mut self, world: &'w mut World, entity: Entity, ) -> Result<<D as QueryData>::Item<'w, '_>, QueryEntityError>
Sourcepub fn get_many_mut<'w, const N: usize>(
&mut self,
world: &'w mut World,
entities: [Entity; N],
) -> Result<[<D as QueryData>::Item<'w, '_>; N], QueryEntityError>where
D: IterQueryData,
pub fn get_many_mut<'w, const N: usize>(
&mut self,
world: &'w mut World,
entities: [Entity; N],
) -> Result<[<D as QueryData>::Item<'w, '_>; N], QueryEntityError>where
D: IterQueryData,
Returns the query results for the given array of Entity.
In case of a nonexisting entity or mismatched component, a QueryEntityError is
returned instead.
use bevy_ecs::prelude::*;
use bevy_ecs::query::QueryEntityError;
#[derive(Component, PartialEq, Debug)]
struct A(usize);
let mut world = World::new();
let entities: Vec<Entity> = (0..3).map(|i|world.spawn(A(i)).id()).collect();
let entities: [Entity; 3] = entities.try_into().unwrap();
world.spawn(A(73));
let mut query_state = world.query::<&mut A>();
let mut mutable_component_values = query_state.get_many_mut(&mut world, entities).unwrap();
for mut a in &mut mutable_component_values {
a.0 += 5;
}
let component_values = query_state.get_many(&world, entities).unwrap();
assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
let wrong_entity = Entity::from_raw_u32(57).unwrap();
let invalid_entity = world.spawn_empty().id();
assert_eq!(match query_state.get_many(&mut world, [wrong_entity]).unwrap_err() {QueryEntityError::NotSpawned(error) => error.entity(), _ => panic!()}, wrong_entity);
assert_eq!(match query_state.get_many_mut(&mut world, [invalid_entity]).unwrap_err() {QueryEntityError::QueryDoesNotMatch(entity, _) => entity, _ => panic!()}, invalid_entity);
assert_eq!(query_state.get_many_mut(&mut world, [entities[0], entities[0]]).unwrap_err(), QueryEntityError::AliasedMutability(entities[0]));Sourcepub fn get_many_unique_mut<'w, const N: usize>(
&mut self,
world: &'w mut World,
entities: UniqueEntityEquivalentArray<Entity, N>,
) -> Result<[<D as QueryData>::Item<'w, '_>; N], QueryEntityError>where
D: IterQueryData,
pub fn get_many_unique_mut<'w, const N: usize>(
&mut self,
world: &'w mut World,
entities: UniqueEntityEquivalentArray<Entity, N>,
) -> Result<[<D as QueryData>::Item<'w, '_>; N], QueryEntityError>where
D: IterQueryData,
Returns the query results for the given UniqueEntityArray.
In case of a nonexisting entity or mismatched component, a QueryEntityError is
returned instead.
use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};
#[derive(Component, PartialEq, Debug)]
struct A(usize);
let mut world = World::new();
let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();
let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();
world.spawn(A(73));
let mut query_state = world.query::<&mut A>();
let mut mutable_component_values = query_state.get_many_unique_mut(&mut world, entity_set).unwrap();
for mut a in &mut mutable_component_values {
a.0 += 5;
}
let component_values = query_state.get_many_unique(&world, entity_set).unwrap();
assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
let wrong_entity = Entity::from_raw_u32(57).unwrap();
let invalid_entity = world.spawn_empty().id();
assert_eq!(match query_state.get_many_unique(&mut world, UniqueEntityArray::from([wrong_entity])).unwrap_err() {QueryEntityError::NotSpawned(error) => error.entity(), _ => panic!()}, wrong_entity);
assert_eq!(match query_state.get_many_unique_mut(&mut world, UniqueEntityArray::from([invalid_entity])).unwrap_err() {QueryEntityError::QueryDoesNotMatch(entity, _) => entity, _ => panic!()}, invalid_entity);Sourcepub fn get_manual<'w>(
&self,
world: &'w World,
entity: Entity,
) -> Result<<<D as QueryData>::ReadOnly as QueryData>::Item<'w, '_>, QueryEntityError>
pub fn get_manual<'w>( &self, world: &'w World, entity: Entity, ) -> Result<<<D as QueryData>::ReadOnly as QueryData>::Item<'w, '_>, QueryEntityError>
Gets the query result for the given World and Entity.
This method is slightly more efficient than QueryState::get in some situations, since
it does not update this instance’s internal cache. This method will return an error if entity
belongs to an archetype that has not been cached.
To ensure that the cache is up to date, call QueryState::update_archetypes before this method.
The cache is also updated in QueryState::new, QueryState::get, or any method with mutable
access to self.
This can only be called for read-only queries, see Self::get_mut for mutable queries.
This is always guaranteed to run in O(1) time.
Sourcepub unsafe fn get_unchecked<'w>(
&mut self,
world: UnsafeWorldCell<'w>,
entity: Entity,
) -> Result<<D as QueryData>::Item<'w, '_>, QueryEntityError>
pub unsafe fn get_unchecked<'w>( &mut self, world: UnsafeWorldCell<'w>, entity: Entity, ) -> Result<<D as QueryData>::Item<'w, '_>, QueryEntityError>
Sourcepub fn iter<'w, 's>(
&'s mut self,
world: &'w World,
) -> QueryIter<'w, 's, <D as QueryData>::ReadOnly, F> ⓘ
pub fn iter<'w, 's>( &'s mut self, world: &'w World, ) -> QueryIter<'w, 's, <D as QueryData>::ReadOnly, F> ⓘ
Returns an Iterator over the query results for the given World.
This can only be called for read-only queries, see Self::iter_mut for write-queries.
If you need to iterate multiple times at once but get borrowing errors,
consider using Self::update_archetypes followed by multiple Self::iter_manual calls.
Examples found in repository?
95fn modify_selected_component(world: &mut World) {
96 // We're using keyboard input to trigger modifications for simplicity.
97 let button_input = world.resource::<ButtonInput<KeyCode>>();
98 let direction_of_modification = if button_input.pressed(KeyCode::ArrowUp) {
99 1.0
100 } else if button_input.pressed(KeyCode::ArrowDown) {
101 -1.0
102 } else {
103 return; // No modification requested
104 };
105
106 let selected = world.resource::<SelectedComponent>().clone();
107
108 let mut sprite_query = world.query_filtered::<Entity, With<Sprite>>();
109
110 // This entity should generally be gathered via UI selection in a real application
111 let entity = sprite_query.iter(world).next().unwrap();
112
113 // We could cheat and use `TypeId::of::<T>()` to get the type ID of a known type,
114 // but real applications identify types by name (from a UI dropdown, text entry or a script).
115 let type_name = match selected {
116 // Note that Bevy's native types are registered under their full subcrate paths:
117 // `bevy_transform`, not `bevy::transform`, `bevy::prelude`, or `bevy_transform::prelude`.
118 // You can use `<T as TypePath>::type_path()` to look this up.
119 SelectedComponent::Transform => "bevy_transform::components::transform::Transform",
120 SelectedComponent::Sprite => "bevy_sprite::sprite::Sprite",
121 };
122
123 // Then, we need to use a type registry to resolve the type name to a `TypeId`.
124 // Types are (for the most part) registered automatically by Bevy,
125 // but you can also register your own types using `App::register_type`.
126 // Generic types always need to be registered manually;
127 // if a type is not showing up in your tool, check if that's the problem.
128 // You can check which types are registered by calling `TypeRegistry::iter()`,
129 // and then use the `Debug` impl for `TypeRegistration` objects to see their names and paths.
130 let app_registry = world.resource::<AppTypeRegistry>().clone();
131 let type_id = app_registry
132 .read()
133 .get_with_type_path(type_name)
134 .expect("Type was not registered, or its full path was ambiguous")
135 .type_id();
136
137 let mut reflected_component: Mut<dyn Reflect> = world.get_reflect_mut(entity, type_id).unwrap();
138
139 match selected {
140 // Downcasting is the easy path:
141 // if you happen to know the type, you can downcast and modify directly.
142 // The problem is that each of these paths would need to be hard-coded (or rely on extensive code-gen),
143 // largely defeating the purpose of using reflection in the first place.
144 SelectedComponent::Sprite => {
145 // Make sure that the type matches the component type you requested to modify.
146 // In a real project, you would want to handle this gracefully.
147 // Downcasting converts the value *directly* into a specified concrete type,
148 // allowing you to escape back into faster, strongly-typed code.
149 let downcast_sprite: &mut Sprite =
150 reflected_component.downcast_mut::<Sprite>().unwrap();
151 // Be careful not to modify a copy of the color — use `&mut`!
152 let color = &mut downcast_sprite.color;
153
154 let new_alpha = (color.alpha() + 0.01 * direction_of_modification).clamp(0.0, 1.0);
155 color.set_alpha(new_alpha);
156 }
157 // This arm demonstrates the more realistic, generic pattern:
158 // walking the reflected type info to find fields to modify.
159 // The benefit is that we can use these patterns
160 // to operate over *any* data based on our knowledge of its shape (recorded using reflection),
161 // without needing to know the concrete type at compile time.
162 SelectedComponent::Transform => {
163 let reflect_mut: ReflectMut<'_> = reflected_component.reflect_mut();
164 // In the fully generic case, we would need to match on the `ReflectMut` variants
165 // and handle each of the arms exhaustively.
166 // `struct_mut` is of type `&mut dyn Struct`, one of a number
167 // of traits that encodes the logic of Rust's type system into a runtime representation.
168 let ReflectMut::Struct(struct_mut) = reflect_mut else {
169 error!("Expected the Transform component type to be a struct");
170 return;
171 };
172
173 // Get the `translation` field as a `&mut dyn PartialReflect`,
174 // which is a type-erased representation of a value that can be modified.
175 let translation_field = struct_mut.field_mut("translation").unwrap();
176
177 // Now, we can repeat the process to get the `y` field of the `translation` Vec3
178 // In a real application, this would probably be done via a recursive function!
179 let ReflectMut::Struct(translation_struct) = translation_field.reflect_mut() else {
180 error!("Expected the translation field to be a struct");
181 return;
182 };
183
184 // We could downcast to an f32 again here, but that would be cheating!
185 // How do you generalize this sort of operation, if, for example,
186 // you wanted to build a generic inspector that could modify any numeric field of any component type?
187 // The solution lies in the way that Bevy can reflect *traits* as well as types,
188 // allowing type owners to define and register additional behavior for their types.
189 // This data is registered automatically at compile time using an inventory-like solution,
190 // and operates on a per-type x per-trait basis,
191 // just like ordinary type reflection.
192 //
193 // We want to increase or decrease the value here,
194 // so we need the `AddAssign` trait
195 // which are already implemented for f32.
196 //
197 // But `AddAssign` is not a supertrait of `PartialReflect`!
198 // We don't have access to its methods! How could that possibly work?
199 //
200 // The solution is again to register the compile time information that we want to use at runtime;
201 // storing function pointers to the trait methods in the type registry.
202 // In order to make this work, we need shadow "reflect" versions of the traits we want to use at runtime.
203 // Bevy provides a few of these out of the box, including `ReflectAddAssign` and `ReflectSubAssign`.
204 // That's what the `#[reflect(Add)]` attributes that you see scattered about in Bevy's source code are doing:
205 // generating implementations of the reflect versions of the traits, so they can later be registered and used at runtime.
206 //
207 // For more information, see the `type_data` example.
208 let y_field: &mut dyn PartialReflect = translation_struct.field_mut("y").unwrap();
209 let field_type_id = y_field
210 .get_represented_type_info()
211 .expect("Found a dynamic type unexpectedly")
212 .type_id();
213
214 let add_assign_trait_data = app_registry
215 .read()
216 .get_type_data::<ReflectAddAssign>(field_type_id)
217 .expect("f32 failed to register ReflectAddAssign")
218 .clone();
219
220 // We need to operate on the value as a concrete type,
221 // so we need to convert it into the more powerful &dyn Reflect type.
222 let y_field: &mut dyn Reflect = y_field.try_as_reflect_mut().expect(
223 "Found a dynamic type unexpectedly, but we need a concrete type to modify it",
224 );
225
226 // We're still cheating a bit here!
227 // By doing this we just *assume* that there's an f32 value when trying to determine what to add to the field.
228 // We *could* try all of the common numeric types, but that would be slow and non-extensible.
229 //
230 // In a real workflow, you would want a dedicated trait with additional methods that exposes
231 // something like dedicated `increment` and `decrement` methods, which handle the type-specific logic of how to modify the value.
232 // Remember to register that trait, and create your own analog of `ReflectAddAssign` for it!
233 //
234 // We don't do that here to avoid making this example *even more* complicated.
235 const MAGNITUDE_OF_MODIFICATION: f32 = 10.;
236 let delta = direction_of_modification * MAGNITUDE_OF_MODIFICATION;
237 let boxed_delta: Box<dyn PartialReflect> = Box::new(delta);
238 add_assign_trait_data
239 .add_assign(y_field, boxed_delta)
240 .expect("We cheated and know the types match, so this should always succeed.");
241 }
242 }
243}Sourcepub fn iter_mut<'w, 's>(
&'s mut self,
world: &'w mut World,
) -> QueryIter<'w, 's, D, F> ⓘ
pub fn iter_mut<'w, 's>( &'s mut self, world: &'w mut World, ) -> QueryIter<'w, 's, D, F> ⓘ
Returns an Iterator over the query results for the given World.
This iterator is always guaranteed to return results from each matching entity once and only once. Iteration order is not guaranteed.
Examples found in repository?
69fn main() {
70 let mut world = World::new();
71 let mut lines = std::io::stdin().lines();
72 let mut component_names = HashMap::<String, ComponentId>::new();
73 let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
74 let mut event_names = HashMap::<String, EventKey>::new();
75
76 println!("{PROMPT}");
77 loop {
78 print!("\n> ");
79 let _ = std::io::stdout().flush();
80 let Some(Ok(line)) = lines.next() else {
81 return;
82 };
83
84 if line.is_empty() {
85 return;
86 };
87
88 let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
89 match &line.chars().next() {
90 Some('c') => println!("{COMPONENT_PROMPT}"),
91 Some('s') => println!("{ENTITY_PROMPT}"),
92 Some('q') => println!("{QUERY_PROMPT}"),
93 Some('e') => println!("{EVENT_PROMPT}"),
94 Some('t') => println!("{EMIT_PROMPT}"),
95 _ => println!("{PROMPT}"),
96 }
97 continue;
98 };
99
100 match &first[0..1] {
101 "c" => {
102 rest.split(',').for_each(|component| {
103 let mut component = component.split_whitespace();
104 let Some(name) = component.next() else {
105 return;
106 };
107 let size = match component.next().map(str::parse) {
108 Some(Ok(size)) => size,
109 _ => 0,
110 };
111 // Register our new component to the world with a layout specified by its size
112 // SAFETY: [u64] is Send + Sync
113 let id = world.register_component_with_descriptor(unsafe {
114 ComponentDescriptor::new_with_layout(
115 name.to_string(),
116 StorageType::Table,
117 Layout::array::<u64>(size).unwrap(),
118 None,
119 true,
120 false,
121 ComponentCloneBehavior::Default,
122 None,
123 )
124 });
125 let Some(info) = world.components().get_info(id) else {
126 return;
127 };
128 component_names.insert(name.to_string(), id);
129 component_info.insert(id, info.clone());
130 println!("Component {} created with id: {}", name, id.index());
131 });
132 }
133 "s" => {
134 let mut to_insert_ids = Vec::new();
135 let mut to_insert_data = Vec::new();
136 rest.split(',').for_each(|component| {
137 let mut component = component.split_whitespace();
138 let Some(name) = component.next() else {
139 return;
140 };
141
142 // Get the id for the component with the given name
143 let Some(&id) = component_names.get(name) else {
144 println!("Component {name} does not exist");
145 return;
146 };
147
148 // Calculate the length for the array based on the layout created for this component id
149 let info = world.components().get_info(id).unwrap();
150 let len = info.layout().size() / size_of::<u64>();
151 let mut values: Vec<u64> = component
152 .take(len)
153 .filter_map(|value| value.parse::<u64>().ok())
154 .collect();
155 values.resize(len, 0);
156
157 // Collect the id and array to be inserted onto our entity
158 to_insert_ids.push(id);
159 to_insert_data.push(values);
160 });
161
162 let mut entity = world.spawn_empty();
163
164 // Construct an `OwningPtr` for each component in `to_insert_data`
165 let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
166
167 // SAFETY:
168 // - Component ids have been taken from the same world
169 // - Each array is created to the layout specified in the world
170 unsafe {
171 entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
172 }
173
174 println!("Entity spawned with id: {}", entity.id());
175 }
176 "q" => {
177 let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
178 parse_query(rest, &mut builder, &component_names);
179 let mut query = builder.build();
180 query.iter_mut(&mut world).for_each(|filtered_entity| {
181 let terms = filtered_entity
182 .access()
183 .try_iter_access()
184 .unwrap()
185 .map(|component_access| {
186 let id = *component_access.index();
187 let ptr = filtered_entity.get_by_id(id).unwrap();
188 let info = component_info.get(&id).unwrap();
189 let len = info.layout().size() / size_of::<u64>();
190
191 // SAFETY:
192 // - All components are created with layout [u64]
193 // - len is calculated from the component descriptor
194 let data = unsafe {
195 std::slice::from_raw_parts_mut(
196 ptr.assert_unique().as_ptr().cast::<u64>(),
197 len,
198 )
199 };
200
201 // If we have write access, increment each value once
202 if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
203 data.iter_mut().for_each(|data| {
204 *data += 1;
205 });
206 }
207
208 format!("{}: {:?}", info.name(), data[0..len].to_vec())
209 })
210 .collect::<Vec<_>>()
211 .join(", ");
212
213 println!("{}: {}", filtered_entity.id(), terms);
214 });
215 }
216 "e" => {
217 rest.split(',').for_each(|event| {
218 let name = event.trim();
219 if name.is_empty() {
220 return;
221 }
222
223 // Register a ComponentId for this event, no Rust type needed.
224 // SAFETY: ZST with no drop
225 let event_component_id = world.register_component_with_descriptor(unsafe {
226 ComponentDescriptor::new_with_layout(
227 format!("event:{name}"),
228 StorageType::Table,
229 Layout::new::<()>(),
230 None,
231 false,
232 false,
233 ComponentCloneBehavior::Ignore,
234 None,
235 )
236 });
237 // SAFETY: event_component_id was just registered for this event
238 let event_key = unsafe { EventKey::new(event_component_id) };
239 event_names.insert(name.to_string(), event_key);
240
241 // Build a dynamic observer that prints when the event fires.
242 let runner: ObserverRunner = |mut world, _observer, ctx, _event, _trigger| {
243 println!(" Observer fired!");
244 if let Some(mut counts) = world.get_resource_mut::<EventFireCount>() {
245 *counts.0.entry(ctx.event_key).or_insert(0) += 1;
246 }
247 };
248
249 // SAFETY: event_key was just registered, runner ignores pointers
250 let observer =
251 unsafe { Observer::with_dynamic_runner(runner).with_event_key(event_key) };
252 world.spawn(observer);
253
254 println!(
255 "Event '{name}' registered (key: {}) with a dynamic observer",
256 event_component_id.index()
257 );
258 });
259
260 // Ensure the counter resource exists.
261 world.init_resource::<EventFireCount>();
262 }
263 "t" => {
264 let name = rest.trim();
265 let Some(&event_key) = event_names.get(name) else {
266 println!(
267 "Event '{name}' does not exist. Register it first with 'event {name}'"
268 );
269 continue;
270 };
271
272 let mut event_data = ();
273 let mut trigger_data = ();
274 // SAFETY: event_key was registered in this world, both pointers are valid ZSTs
275 unsafe {
276 world.trigger_dynamic(
277 event_key,
278 PtrMut::from(&mut event_data),
279 PtrMut::from(&mut trigger_data),
280 );
281 }
282
283 let count = world
284 .get_resource::<EventFireCount>()
285 .map_or(0, |c| c.0.get(&event_key).copied().unwrap_or(0));
286 println!("Event '{name}' triggered ({count} fires)");
287 }
288 _ => continue,
289 }
290 }
291}Sourcepub fn iter_manual<'w, 's>(
&'s self,
world: &'w World,
) -> QueryIter<'w, 's, <D as QueryData>::ReadOnly, F> ⓘ
pub fn iter_manual<'w, 's>( &'s self, world: &'w World, ) -> QueryIter<'w, 's, <D as QueryData>::ReadOnly, F> ⓘ
Returns an Iterator over the query results for the given World without updating the query’s archetypes.
Archetypes must be manually updated before by using Self::update_archetypes.
This iterator is always guaranteed to return results from each matching entity once and only once. Iteration order is not guaranteed.
This can only be called for read-only queries.
Sourcepub fn iter_combinations<'w, 's, const K: usize>(
&'s mut self,
world: &'w World,
) -> QueryCombinationIter<'w, 's, <D as QueryData>::ReadOnly, F, K> ⓘ
pub fn iter_combinations<'w, 's, const K: usize>( &'s mut self, world: &'w World, ) -> QueryCombinationIter<'w, 's, <D as QueryData>::ReadOnly, F, K> ⓘ
Returns an Iterator over all possible combinations of K query results without repetition.
This can only be called for read-only queries.
A combination is an arrangement of a collection of items where order does not matter.
K is the number of items that make up each subset, and the number of items returned by the iterator.
N is the number of total entities output by query.
For example, given the list [1, 2, 3, 4], where K is 2, the combinations without repeats are
[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4].
And in this case, N would be defined as 4 since the size of the input list is 4.
For combinations of size K of query taking N inputs, you will get:
- if
K == N: one combination of all query results - if
K < N: all possibleK-sized combinations of query results, without repetition - if
K > N: empty set (noK-sized combinations exist)
The iter_combinations method does not guarantee order of iteration.
This iterator is always guaranteed to return results from each unique pair of matching entities. Iteration order is not guaranteed.
This can only be called for read-only queries, see Self::iter_combinations_mut for
write-queries.
Sourcepub fn iter_combinations_mut<'w, 's, const K: usize>(
&'s mut self,
world: &'w mut World,
) -> QueryCombinationIter<'w, 's, D, F, K> ⓘwhere
D: IterQueryData,
pub fn iter_combinations_mut<'w, 's, const K: usize>(
&'s mut self,
world: &'w mut World,
) -> QueryCombinationIter<'w, 's, D, F, K> ⓘwhere
D: IterQueryData,
Returns an Iterator over all possible combinations of K query results without repetition.
A combination is an arrangement of a collection of items where order does not matter.
K is the number of items that make up each subset, and the number of items returned by the iterator.
N is the number of total entities output by query.
For example, given the list [1, 2, 3, 4], where K is 2, the combinations without repeats are
[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4].
And in this case, N would be defined as 4 since the size of the input list is 4.
For combinations of size K of query taking N inputs, you will get:
- if
K == N: one combination of all query results - if
K < N: all possibleK-sized combinations of query results, without repetition - if
K > N: empty set (noK-sized combinations exist)
The iter_combinations_mut method does not guarantee order of iteration.
Sourcepub fn iter_many<'w, 's, EntityList>(
&'s mut self,
world: &'w World,
entities: EntityList,
) -> QueryManyIter<'w, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter> ⓘ
pub fn iter_many<'w, 's, EntityList>( &'s mut self, world: &'w World, entities: EntityList, ) -> QueryManyIter<'w, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter> ⓘ
Returns an Iterator over the read-only query items generated from an Entity list.
Items are returned in the order of the list of entities.
In case of a nonexisting entity or mismatched component, a QueryEntityError is generated instead.
If you need to iterate multiple times at once but get borrowing errors,
consider using Self::update_archetypes followed by multiple Self::iter_many_manual calls.
§See also
iter_many_mutto get mutable query items.
Sourcepub fn iter_many_manual<'w, 's, EntityList>(
&'s self,
world: &'w World,
entities: EntityList,
) -> QueryManyIter<'w, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter> ⓘ
pub fn iter_many_manual<'w, 's, EntityList>( &'s self, world: &'w World, entities: EntityList, ) -> QueryManyIter<'w, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter> ⓘ
Returns an Iterator over the read-only query items generated from an Entity list.
Items are returned in the order of the list of entities.
In case of a nonexisting entity or mismatched component, a QueryEntityError is generated instead.
If world archetypes changed since Self::update_archetypes was last called,
this will skip entities contained in new archetypes.
This can only be called for read-only queries.
§See also
iter_manyto update archetypes.iter_manualto iterate over all query items.
Sourcepub fn iter_many_mut<'w, 's, EntityList>(
&'s mut self,
world: &'w mut World,
entities: EntityList,
) -> QueryManyIter<'w, 's, D, F, <EntityList as IntoIterator>::IntoIter> ⓘ
pub fn iter_many_mut<'w, 's, EntityList>( &'s mut self, world: &'w mut World, entities: EntityList, ) -> QueryManyIter<'w, 's, D, F, <EntityList as IntoIterator>::IntoIter> ⓘ
Returns an iterator over the query items generated from an Entity list.
Items are returned in the order of the list of entities.
In case of a nonexisting entity or mismatched component, a QueryEntityError is generated instead.
Sourcepub fn iter_many_unique<'w, 's, EntityList>(
&'s mut self,
world: &'w World,
entities: EntityList,
) -> QueryManyUniqueIter<'w, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter> ⓘwhere
EntityList: EntitySet,
pub fn iter_many_unique<'w, 's, EntityList>(
&'s mut self,
world: &'w World,
entities: EntityList,
) -> QueryManyUniqueIter<'w, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter> ⓘwhere
EntityList: EntitySet,
Returns an Iterator over the unique read-only query items generated from an EntitySet.
Items are returned in the order of the list of entities.
In case of a nonexisting entity or mismatched component, a QueryEntityError is generated instead.
§See also
iter_many_unique_mutto get mutable query items.
Sourcepub fn iter_many_unique_manual<'w, 's, EntityList>(
&'s self,
world: &'w World,
entities: EntityList,
) -> QueryManyUniqueIter<'w, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter> ⓘwhere
EntityList: EntitySet,
pub fn iter_many_unique_manual<'w, 's, EntityList>(
&'s self,
world: &'w World,
entities: EntityList,
) -> QueryManyUniqueIter<'w, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter> ⓘwhere
EntityList: EntitySet,
Returns an Iterator over the unique read-only query items generated from an EntitySet.
Items are returned in the order of the list of entities.
In case of a nonexisting entity or mismatched component, a QueryEntityError is generated instead.
If world archetypes changed since Self::update_archetypes was last called,
this will skip entities contained in new archetypes.
This can only be called for read-only queries.
§See also
iter_many_uniqueto update archetypes.iter_manyto iterate over a non-unique entity list.iter_manualto iterate over all query items.
Sourcepub fn iter_many_unique_mut<'w, 's, EntityList>(
&'s mut self,
world: &'w mut World,
entities: EntityList,
) -> QueryManyUniqueIter<'w, 's, D, F, <EntityList as IntoIterator>::IntoIter> ⓘwhere
EntityList: EntitySet,
D: IterQueryData,
pub fn iter_many_unique_mut<'w, 's, EntityList>(
&'s mut self,
world: &'w mut World,
entities: EntityList,
) -> QueryManyUniqueIter<'w, 's, D, F, <EntityList as IntoIterator>::IntoIter> ⓘwhere
EntityList: EntitySet,
D: IterQueryData,
Returns an iterator over the unique query items generated from an EntitySet.
Items are returned in the order of the list of entities.
In case of a nonexisting entity or mismatched component, a QueryEntityError is generated instead.
Sourcepub unsafe fn iter_unchecked<'w, 's>(
&'s mut self,
world: UnsafeWorldCell<'w>,
) -> QueryIter<'w, 's, D, F> ⓘ
pub unsafe fn iter_unchecked<'w, 's>( &'s mut self, world: UnsafeWorldCell<'w>, ) -> QueryIter<'w, 's, D, F> ⓘ
Returns an Iterator over the query results for the given World.
This iterator is always guaranteed to return results from each matching entity once and only once. Iteration order is not guaranteed.
§Safety
This does not check for mutable query correctness. To be safe, make sure mutable queries have unique access to the components they query.
Sourcepub unsafe fn iter_combinations_unchecked<'w, 's, const K: usize>(
&'s mut self,
world: UnsafeWorldCell<'w>,
) -> QueryCombinationIter<'w, 's, D, F, K> ⓘwhere
D: IterQueryData,
pub unsafe fn iter_combinations_unchecked<'w, 's, const K: usize>(
&'s mut self,
world: UnsafeWorldCell<'w>,
) -> QueryCombinationIter<'w, 's, D, F, K> ⓘwhere
D: IterQueryData,
Returns an Iterator over all possible combinations of K query results for the
given World without repetition.
This can only be called for read-only queries.
This iterator is always guaranteed to return results from each unique pair of matching entities. Iteration order is not guaranteed.
§Safety
This does not check for mutable query correctness. To be safe, make sure mutable queries have unique access to the components they query.
Sourcepub fn par_iter<'w, 's>(
&'s mut self,
world: &'w World,
) -> QueryParIter<'w, 's, <D as QueryData>::ReadOnly, F>
pub fn par_iter<'w, 's>( &'s mut self, world: &'w World, ) -> QueryParIter<'w, 's, <D as QueryData>::ReadOnly, F>
Returns a parallel iterator over the query results for the given World.
This can only be called for read-only queries, see par_iter_mut for write-queries.
Note that you must use the for_each method to iterate over the
results, see par_iter_mut for an example.
Sourcepub fn par_iter_mut<'w, 's>(
&'s mut self,
world: &'w mut World,
) -> QueryParIter<'w, 's, D, F>where
D: IterQueryData,
pub fn par_iter_mut<'w, 's>(
&'s mut self,
world: &'w mut World,
) -> QueryParIter<'w, 's, D, F>where
D: IterQueryData,
Returns a parallel iterator over the query results for the given World.
This can only be called for mutable queries, see par_iter for read-only-queries.
§Examples
use bevy_ecs::prelude::*;
use bevy_ecs::query::QueryEntityError;
#[derive(Component, PartialEq, Debug)]
struct A(usize);
let mut world = World::new();
let mut query_state = world.query::<&mut A>();
query_state.par_iter_mut(&mut world).for_each(|mut a| {
a.0 += 5;
});
assert_eq!(match query_state.get_many_mut(&mut world, [invalid_entity]).unwrap_err() {QueryEntityError::QueryDoesNotMatch(entity, _) => entity, _ => panic!()}, invalid_entity);§Panics
The ComputeTaskPool is not initialized. If using this from a query that is being
initialized and run from the ECS scheduler, this should never panic.
Sourcepub fn contiguous_iter<'w, 's>(
&'s mut self,
world: &'w World,
) -> Result<QueryContiguousIter<'w, 's, <D as QueryData>::ReadOnly, F>, QueryNotDenseError>
pub fn contiguous_iter<'w, 's>( &'s mut self, world: &'w World, ) -> Result<QueryContiguousIter<'w, 's, <D as QueryData>::ReadOnly, F>, QueryNotDenseError>
Returns a contiguous iterator over the query results for the given World or Err with QueryNotDenseError if
the query is not dense hence not contiguously iterable.
Sourcepub fn contiguous_iter_mut<'w, 's>(
&'s mut self,
world: &'w mut World,
) -> Result<QueryContiguousIter<'w, 's, D, F>, QueryNotDenseError>where
D: ContiguousQueryData,
F: ArchetypeFilter,
pub fn contiguous_iter_mut<'w, 's>(
&'s mut self,
world: &'w mut World,
) -> Result<QueryContiguousIter<'w, 's, D, F>, QueryNotDenseError>where
D: ContiguousQueryData,
F: ArchetypeFilter,
Returns a contiguous iterator over the query results for the given World or Err with QueryNotDenseError if
the query is not dense hence not contiguously iterable.
This can only be called for mutable queries, see Self::contiguous_iter for read-only-queries.
Sourcepub fn contiguous_par_iter<'w, 's>(
&'s mut self,
world: &'w World,
) -> Result<QueryContiguousParIter<'w, 's, <D as QueryData>::ReadOnly, F>, QueryNotDenseError>
pub fn contiguous_par_iter<'w, 's>( &'s mut self, world: &'w World, ) -> Result<QueryContiguousParIter<'w, 's, <D as QueryData>::ReadOnly, F>, QueryNotDenseError>
Returns a parallel contiguous iterator over the query results for the
given World or Err with QueryNotDenseError if the query is
not dense hence not contiguously iterable.
This can only be called for read-only queries. See
Self::contiguous_par_iter_mut for queries that may write to the
components.
Note that you must use the QueryContiguousParIter::for_each method
to iterate over the results. See Self::contiguous_par_iter_mut for
an example.
§Panics
The ComputeTaskPool is not initialized. If using this from a query
that is being initialized and run from the ECS scheduler, this should
never panic.
Sourcepub fn contiguous_par_iter_mut<'w, 's>(
&'s mut self,
world: &'w mut World,
) -> Result<QueryContiguousParIter<'w, 's, D, F>, QueryNotDenseError>where
D: ContiguousQueryData,
F: ArchetypeFilter,
pub fn contiguous_par_iter_mut<'w, 's>(
&'s mut self,
world: &'w mut World,
) -> Result<QueryContiguousParIter<'w, 's, D, F>, QueryNotDenseError>where
D: ContiguousQueryData,
F: ArchetypeFilter,
Returns a parallel contiguous iterator over the query results for the
given World or Err with QueryNotDenseError if the query is
not dense hence not contiguously iterable.
This version of the method is for mutable queries. For read-only
queries, see Self::contiguous_par_iter.
§Examples
use bevy_ecs::prelude::*;
use bevy_ecs::query::QueryEntityError;
#[derive(Component, PartialEq, Debug)]
struct A(usize);
let mut world = World::new();
let mut query_state = world.query::<&mut A>();
query_state.contiguous_par_iter_mut(&mut world).unwrap().for_each(|mut batch| {
for a in batch {
a.0 += 5;
}
});
assert_eq!(match query_state.get_many_mut(&mut world, [invalid_entity]).unwrap_err() {QueryEntityError::QueryDoesNotMatch(entity, _) => entity, _ => panic!()}, invalid_entity);§Panics
The ComputeTaskPool is not initialized. If using this from a query
that is being initialized and run from the ECS scheduler, this should
never panic.
Source§impl<D, F> QueryState<D, F>where
D: QueryData,
F: QueryFilter,
impl<D, F> QueryState<D, F>where
D: QueryData,
F: QueryFilter,
Sourcepub fn single<'w>(
&mut self,
world: &'w World,
) -> Result<<<D as QueryData>::ReadOnly as QueryData>::Item<'w, '_>, QuerySingleError>
pub fn single<'w>( &mut self, world: &'w World, ) -> Result<<<D as QueryData>::ReadOnly as QueryData>::Item<'w, '_>, QuerySingleError>
Returns a single immutable query result when there is exactly one entity matching the query.
This can only be called for read-only queries,
see single_mut for write-queries.
If the number of query results is not exactly one, a QuerySingleError is returned
instead.
§Example
Sometimes, you might want to handle the error in a specific way, generally by spawning the missing entity.
use bevy_ecs::prelude::*;
use bevy_ecs::query::QuerySingleError;
#[derive(Component)]
struct A(usize);
fn my_system(query: Query<&A>, mut commands: Commands) {
match query.single() {
Ok(a) => (), // Do something with `a`
Err(err) => match err {
QuerySingleError::NoEntities(_) => {
commands.spawn(A(0));
}
QuerySingleError::MultipleEntities(_) => panic!("Multiple entities found!"),
},
}
}However in most cases, this error can simply be handled with a graceful early return.
If this is an expected failure mode, you can do this using the let else pattern like so:
use bevy_ecs::prelude::*;
#[derive(Component)]
struct A(usize);
fn my_system(query: Query<&A>) {
let Ok(a) = query.single() else {
return;
};
// Do something with `a`
}If this is unexpected though, you should probably use the ? operator
in combination with Bevy’s error handling apparatus.
use bevy_ecs::prelude::*;
#[derive(Component)]
struct A(usize);
fn my_system(query: Query<&A>) -> Result {
let a = query.single()?;
// Do something with `a`
Ok(())
}This allows you to globally control how errors are handled in your application,
by setting up a custom error handler.
See the bevy_ecs::error module docs for more information!
Commonly, you might want to panic on an error during development, but log the error and continue
execution in production.
Simply unwrapping the Result also works, but should generally be reserved for tests.
Sourcepub fn single_mut<'w>(
&mut self,
world: &'w mut World,
) -> Result<<D as QueryData>::Item<'w, '_>, QuerySingleError>where
D: IterQueryData,
pub fn single_mut<'w>(
&mut self,
world: &'w mut World,
) -> Result<<D as QueryData>::Item<'w, '_>, QuerySingleError>where
D: IterQueryData,
Returns a single mutable query result when there is exactly one entity matching the query.
If the number of query results is not exactly one, a QuerySingleError is returned
instead.
§Examples
Please see Query::single for advice on handling the error.
Examples found in repository?
49fn init_window_pos(app: &mut App) {
50 let world = app.world_mut();
51 let Some(window_settings) = world.get_resource::<WindowSettings>() else {
52 return;
53 };
54 let window_settings = window_settings.clone();
55
56 let Ok(mut window) = world.query::<&mut Window>().single_mut(world) else {
57 warn!("window not found");
58 return;
59 };
60
61 if let Some(position) = window_settings.position {
62 window.position = WindowPosition::new(position);
63 }
64
65 if let Some(size) = window_settings.size {
66 window.resolution = WindowResolution::new(size.x, size.y);
67 }
68
69 window.mode = if window_settings.fullscreen {
70 WindowMode::BorderlessFullscreen(MonitorSelection::Current)
71 } else {
72 WindowMode::Windowed
73 };
74}Sourcepub unsafe fn single_unchecked<'w>(
&mut self,
world: UnsafeWorldCell<'w>,
) -> Result<<D as QueryData>::Item<'w, '_>, QuerySingleError>where
D: IterQueryData,
pub unsafe fn single_unchecked<'w>(
&mut self,
world: UnsafeWorldCell<'w>,
) -> Result<<D as QueryData>::Item<'w, '_>, QuerySingleError>where
D: IterQueryData,
Returns a query result when there is exactly one entity matching the query.
If the number of query results is not exactly one, a QuerySingleError is returned
instead.
§Safety
This does not check for mutable query correctness. To be safe, make sure mutable queries have unique access to the components they query.
Sourcepub unsafe fn single_unchecked_manual<'w>(
&self,
world: UnsafeWorldCell<'w>,
last_run: Tick,
this_run: Tick,
) -> Result<<D as QueryData>::Item<'w, '_>, QuerySingleError>where
D: IterQueryData,
pub unsafe fn single_unchecked_manual<'w>(
&self,
world: UnsafeWorldCell<'w>,
last_run: Tick,
this_run: Tick,
) -> Result<<D as QueryData>::Item<'w, '_>, QuerySingleError>where
D: IterQueryData,
Returns a query result when there is exactly one entity matching the query, where the last change and the current change tick are given.
If the number of query results is not exactly one, a QuerySingleError is returned
instead.
§Safety
This does not check for mutable query correctness. To be safe, make sure mutable queries
have unique access to the components they query.
This does not validate that world.id() matches self.world_id. Calling this on a world
with a mismatched WorldId is unsound.
Trait Implementations§
Source§impl<D, F> Debug for QueryState<D, F>where
D: QueryData,
F: QueryFilter,
impl<D, F> Debug for QueryState<D, F>where
D: QueryData,
F: QueryFilter,
Source§impl<D, F> From<QueryBuilder<'_, D, F>> for QueryState<D, F>where
D: QueryData,
F: QueryFilter,
impl<D, F> From<QueryBuilder<'_, D, F>> for QueryState<D, F>where
D: QueryData,
F: QueryFilter,
Source§fn from(value: QueryBuilder<'_, D, F>) -> QueryState<D, F>
fn from(value: QueryBuilder<'_, D, F>) -> QueryState<D, F>
Source§impl<D, F> FromWorld for QueryState<D, F>where
D: QueryData,
F: QueryFilter,
impl<D, F> FromWorld for QueryState<D, F>where
D: QueryData,
F: QueryFilter,
Source§fn from_world(world: &mut World) -> QueryState<D, F>
fn from_world(world: &mut World) -> QueryState<D, F>
Self using data from the given World.impl<D, F> ReadOnlySystemParam for &mut QueryState<D, F>where
D: QueryData + 'static,
F: QueryFilter + 'static,
Source§impl<D, F> SystemParam for &mut QueryState<D, F>where
D: QueryData + 'static,
F: QueryFilter + 'static,
impl<D, F> SystemParam for &mut QueryState<D, F>where
D: QueryData + 'static,
F: QueryFilter + 'static,
Source§type State = QueryState<D, F>
type State = QueryState<D, F>
Source§type Item<'world, 'state> = &'state mut QueryState<D, F>
type Item<'world, 'state> = &'state mut QueryState<D, F>
Self, instantiated with new lifetimes. Read moreSource§fn init_state(
world: &mut World,
) -> <&mut QueryState<D, F> as SystemParam>::State
fn init_state( world: &mut World, ) -> <&mut QueryState<D, F> as SystemParam>::State
State.Source§fn init_access(
_state: &<&mut QueryState<D, F> as SystemParam>::State,
_system_meta: &mut SystemMeta,
_system_access: &mut SystemAccess,
_world: &mut World,
)
fn init_access( _state: &<&mut QueryState<D, F> as SystemParam>::State, _system_meta: &mut SystemMeta, _system_access: &mut SystemAccess, _world: &mut World, )
Source§unsafe fn get_param<'world, 'state>(
state: &'state mut <&mut QueryState<D, F> as SystemParam>::State,
_system_meta: &SystemMeta,
_world: UnsafeWorldCell<'world>,
_change_tick: Tick,
) -> Result<<&mut QueryState<D, F> as SystemParam>::Item<'world, 'state>, SystemParamValidationError>
unsafe fn get_param<'world, 'state>( state: &'state mut <&mut QueryState<D, F> as SystemParam>::State, _system_meta: &SystemMeta, _world: UnsafeWorldCell<'world>, _change_tick: Tick, ) -> Result<<&mut QueryState<D, F> as SystemParam>::Item<'world, 'state>, SystemParamValidationError>
SystemParamFunction. Read moreSource§fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World)
fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World)
SystemParam’s state.
This is used to apply Commands during ApplyDeferred.Source§fn queue(
state: &mut Self::State,
system_meta: &SystemMeta,
world: DeferredWorld<'_>,
)
fn queue( state: &mut Self::State, system_meta: &SystemMeta, world: DeferredWorld<'_>, )
ApplyDeferred.Source§impl<'w, 's, D, F> SystemParamBuilder<Query<'w, 's, D, F>> for QueryState<D, F>where
D: QueryData + 'static,
F: QueryFilter + 'static,
impl<'w, 's, D, F> SystemParamBuilder<Query<'w, 's, D, F>> for QueryState<D, F>where
D: QueryData + 'static,
F: QueryFilter + 'static,
Source§fn build(self, world: &mut World) -> QueryState<D, F>
fn build(self, world: &mut World) -> QueryState<D, F>
World access used by this SystemParam
and creates a new instance of this param’s State.Source§fn build_state(self, world: &mut World) -> SystemState<P>
fn build_state(self, world: &mut World) -> SystemState<P>
SystemState from a SystemParamBuilder.
To create a system, call SystemState::build_system on the result.Source§fn build_system<Marker, In, Out, Func>(
self,
func: Func,
) -> IntoBuilderSystem<Marker, In, Out, Func, Self>where
Self: 'static,
Func: SystemParamFunction<Marker, Param = P>,
fn build_system<Marker, In, Out, Func>(
self,
func: Func,
) -> IntoBuilderSystem<Marker, In, Out, Func, Self>where
Self: 'static,
Func: SystemParamFunction<Marker, Param = P>,
Auto Trait Implementations§
impl<D, F = ()> !RefUnwindSafe for QueryState<D, F>
impl<D, F = ()> !UnwindSafe for QueryState<D, F>
impl<D, F> Freeze for QueryState<D, F>
impl<D, F> Send for QueryState<D, F>
impl<D, F> Sync for QueryState<D, F>
impl<D, F> Unpin for QueryState<D, F>
impl<D, F> UnsafeUnpin for QueryState<D, F>
Blanket Implementations§
Source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
Source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
T ShaderType for self. When used in AsBindGroup
derives, it is safe to assume that all images in self exist.Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
impl<T> ConditionalSend for Twhere
T: Send,
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be
downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further
downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can
then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be
further downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.Source§impl<T> DowncastSend for T
impl<T> DowncastSend for T
Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
impl<S, T> Duplex<S> for Twhere
T: FromSample<S> + ToSample<S>,
impl<T> ErasedDestructor for Twhere
T: 'static,
Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self to use its Binary implementation when Debug-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self to use its Display implementation when
Debug-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self to use its LowerExp implementation when
Debug-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self to use its LowerHex implementation when
Debug-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self to use its Octal implementation when Debug-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self to use its Pointer implementation when
Debug-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self to use its UpperExp implementation when
Debug-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self to use its UpperHex implementation when
Debug-formatted.Source§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T, W> HasTypeWitness<W> for Twhere
W: MakeTypeWitness<Arg = T>,
T: ?Sized,
impl<T, W> HasTypeWitness<W> for Twhere
W: MakeTypeWitness<Arg = T>,
T: ?Sized,
impl<T> HitDataExtra for T
Source§impl<T> Identity for Twhere
T: ?Sized,
impl<T> Identity for Twhere
T: ?Sized,
Source§impl<T> InitializeFromFunction<T> for T
impl<T> InitializeFromFunction<T> for T
Source§fn initialize_from_function(f: fn() -> T) -> T
fn initialize_from_function(f: fn() -> T) -> T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> IntoResult<T> for T
impl<T> IntoResult<T> for T
Source§fn into_result(self) -> Result<T, RunSystemError>
fn into_result(self) -> Result<T, RunSystemError>
Source§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self, then passes self.as_ref() into the pipe function.Source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self, then passes self.as_mut() into the pipe
function.Source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self, then passes self.deref() into the pipe function.impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
impl<T> Settings for T
Source§impl<Ret> SpawnIfAsync<(), Ret> for Ret
impl<Ret> SpawnIfAsync<(), Ret> for Ret
Source§impl<T, O> SuperFrom<T> for Owhere
O: From<T>,
impl<T, O> SuperFrom<T> for Owhere
O: From<T>,
Source§fn super_from(input: T) -> O
fn super_from(input: T) -> O
Source§impl<T, O, M> SuperInto<O, M> for Twhere
O: SuperFrom<T, M>,
impl<T, O, M> SuperInto<O, M> for Twhere
O: SuperFrom<T, M>,
Source§fn super_into(self) -> O
fn super_into(self) -> O
Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B> of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B> of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R> view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R> view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap() only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut() only in debug builds, and is erased in release
builds.Source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref() only in debug builds, and is erased in release
builds.Source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut() only in debug builds, and is erased in release
builds.Source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref() only in debug builds, and is erased in release
builds.