mdeloof / statig

Hierarchical state machines for designing event-driven systems
https://crates.io/crates/statig
MIT License
560 stars 18 forks source link

Multiple refrences with different lifetimes as 'Context' #13

Closed sorenrade closed 1 year ago

sorenrade commented 1 year ago

Hi! I'm liking this library and would like to switch to it but I need to pass multiple references in for context. Creating a type that composes several references like so

struct Context<'a, 'b>{
   foo: &'a mut LargeStruct1,
   bar: &'b mut LargeStruct2
}

won't work since I cant create function-level generic lifetimes. Is there a way around this?

Thanks!

sorenrade commented 1 year ago

Actually, I can't think why it would be necessary to have multiple lifetimes. I think being able to pass multiple references with the same lifetime would be enough. Is this possible?

mdeloof commented 1 year ago

Hi! Yes, it should be possible. When adding your context to an event handler or action, you can use anonymous lifetimes, like this:

#[state]
fn on(context: &mut Context<'_, '_>, event: &Event) -> Response<State> {
    ...
}

The macro will then replace these anonymous lifetimes with the 'ctx lifetime when deriving the context type. So the derived IntoStateMachine trait will look like this:

impl IntoStateMachine for Foo {
    type Context<'ctx> = Context<'ctx, 'ctx>;
    ...
}
sorenrade commented 1 year ago

Ahh nice! That does it thanks!