Lifetimes and `#[derive(WorldQuery)]`
- Dominant language
- Rust
- Stars
- 48.2k
- Forks
- 4.8k
- Avg merge
- 3d 22h
- Merged PRs (30d)
- 161
Description
## 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:
```rust
#[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:
```rust
#[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:
```rust
#[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> {
// ...
}
}
```
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.):
```rust
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.
Contributor guide
Assessment
This issue has not been assessed yet.