issue with references and lifetimes #20072
-
i have a system responsible for progressing through timelines of frames that describe a character ability. these abilities do things that amount to adding components and creating entities. abilities' implementations need data about the world and mutable references to add meshes etc, so the system calls each frame's function with this data for frame in frames {
(frame.function)(
&mut commands,
&camera,
(ability_entity, &ability, &ability_transform),
&mut meshes,
&mut materials,
&asset_server,
)
} pub struct Frame {
frame: usize,
function: fn(
&mut Commands,
&(Entity, &Transform),
(Entity, &Ability, &Transform),
&mut ResMut<Assets<Mesh>>,
&mut ResMut<Assets<StandardMaterial>>,
&Res<AssetServer>,
) -> (),
} however, if i'm implementing a new ability and it needs data that's not already being passed, i have to update the function signature in the i tried creating a context struct and passing the whole thing as one argument so that each function could pull what it needed off the struct and if i added anything i would only have to change one definition // i added this 'a because it complained that the references were missing a lifetime parameter
pub struct AbilityContext<'a> {
camera: &'a (Entity, &'a Transform),
ability: (Entity, &'a Ability, &'a Transform),
meshes: &'a mut ResMut<'a, Assets<Mesh>>,
materials: &'a mut ResMut<'a, Assets<StandardMaterial>>,
asset_server: &'a Res<'a, AssetServer>,
}
// ...
for frame in frames {
(frame.function)(
&mut commands,
&context
)
} but when i try to create this struct, the compiler tells me that my borrowed values do not live long enough. i don't understand lifetimes well enough to know why the references are okay to be passed into the function but not put in the struct. is there another way i can pass this data/these references to each function where i wouldn't need to update each function definition any time i added data? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This likely comes from the fact that you are using one lifetime for everything. For example in
you have
You can most likely fix this by introducing more distinct lifetime parameters like |
Beta Was this translation helpful? Give feedback.
This likely comes from the fact that you are using one lifetime for everything. For example in
you have
'a
for both the lifetime of the reference to the resource and in the resource itself. But the two lifetimes describe different things:You can most likely fix this by introducing more distinct lifetime parameters like
'b
additionally to'a