I tend to represent a lot of programs as state-machines as most of what I write are implementation of protocols. The transaction layer of protocols can typically be implemented as a state-machine of message sequences. Right now, I represent this state-machine using the type state pattern
impl Transaction for StateA {}
impl Transaction for StateB {}
But I was thinking how nice it would be to represent the state transitions as purely sequences of the messages themselves, implemented with tuples + variadic generics + trait specialization and checked at compile time.
trait Transaction { fn next(self: Box<Self>) -> Box<dyn Transaction>; }
impl Transaction for (MessageA, ...MessageB, MessageC)
Implementation where first state is MessageA
, then zero or more MessageB
, terminated by MessageC
.
Then if I want a catch-all for the above implementation I can combine specialization with the variadic
impl<T> Transaction for (...T, MessageC) // default implementation
This will probably never be possible in Rust. But man do I want this.