by cerebellum42 · 6y ago · 0 comments
struct Foo<S> {
state: State<S>,
}
The moment we initialize Foo to take e.g. Green as its parameter, it can now no longer switch to Red in safe Rust. This is what enums are for, and unfortunately we can't use those here.Couldn't you just declare a trait that S must implement and then declare the member in Foo as State<dyn Trait>? That trait would probably also include the next() method mentioned in the example. Of course you'd be adding dynamic dispatch here, but it should work, right?
- Reusing code between states.
- Making callbacks to other APIs during state changes.
I ended up using the standard state pattern described here:
https://doc.rust-lang.org/book/ch17-03-oo-design-patterns.ht...The state pattern is not considered to be idiomatic Rust, but in my experience it works better and is very flexible.
The state pattern has the downside that the type system does not enforce which state changes are allowed.
for
struct State<T> { state: T }
with possible states struct A { id: Uuid }
struct B { id: Uuid }
use a trait trait HasId {
fn id_mut(&mut self) -> &mut Uuid;
}
now you can impl over both A and B impl<T: HasId> for State<T> {
fn new_id(&mut self) { *self.state.id_mut() = Uuid::new_v4() }
}
simplistic example but enough to communicate the idea hopefully.generally, macros makes this kind of thing ergonomic so you can generate the trait implementations and so on. otherwise it's a lot of typing.
don't understand what you mean about making callbacks to other APIs during transitions.
Specially in things like parsing or a network protocol!