Skip to content

Lifetimes and #[derive(WorldQuery)] #9377

Open
@Zeenobit

Description

@Zeenobit

How can Bevy's documentation be improved?

https://docs.rs/bevy/latest/bevy/ecs/query/trait.WorldQuery.html

When using #[derive(WorldQuery)], based on the documentation, we should be using 'static lifetime for all references:

#[derive(WorldQuery)]
struct MyQuery {
    entity: Entity,
    // It is required that all reference lifetimes are explicitly annotated, just like in any
    // struct. Each lifetime should be 'static.
    component_a: &'static ComponentA,
    component_b: &'static ComponentB,
}

However, it seems like you can also use a lifetime parameter:

#[derive(WorldQuery)]
struct MyQuery<'a> {
    entity: Entity,
    component_a: &'a ComponentA,
    component_b: &'a ComponentB,
}

In fact, I've been using this lifetime parameter in my code (without knowing it should be 'static) to allow construction of WorldQuery types from &World. For example:

#[derive(WorldQuery)]
struct PlayerRef<'a> {
    pub entity: Entity,
    pub name: &'a Name,
    // ...
}
impl<'a> PlayerRef<'a> {
    pub fn from_entity_ref(entity: EntityRef<'a>) -> Option<PlayerRef<'a>> {
        // ...
    }
}

I find this pattern useful because it allows these query types be used in systems, as well as any code that has exclusive &World access (such as debug, tests, editor, etc.):

let player = PlayerRef::from_entity(world.entity(entity)).unwrap();
assert_eq!(player.name, ...)

Is this usage an anti-pattern?

  • If so, I think there would be value in additional documentation about why the references have to be 'static despite having the option for them to not be so. Better yet, I'd say the derive macro should check for lifetimes and disallow them if we have to use 'static.
  • Otherwise, if we don't have to use 'static, and this is an acceptable usage, then I propose it should also be documented as such. The statement about references having to be static should be replaced with documentation on the lifetime parameter and how to use it correctly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ECSEntities, components, systems, and eventsC-DocsAn addition or correction to our documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions