A way to implement Retry/Reload functionality

Hey there,

Lately I've been using the pattern bellow a lot, I don't particularly hate it but I'm wondering if there is a better way of doing this, especially regarding the fact that I can't use continue from inside a closure, how else could I do this ?

enum State {
    Foo,
    Bar,
    Baz,
}

struct FooBar(State, u32);

impl FooBar {
    fn process(&mut self) {
        loop {
            break match self.0 {
                State::Foo => todo!(),
                State::Bar => todo!(),
                State::Baz => {
                    // ... do something
                    if self.1 == 10 {
                        self.0 = State::Foo;
                        continue;
                    }
                },
            };
        }
    }
}

You could use ControlFlow in std::ops - Rust in your process method return type, and by doing so you could control the flow even from within a closure.

3 Likes

Your pattern is called "state machine" I would say. You can get some inspirations from crates that implement a state machine for you, or you just write code like you did, which is a state machine and Rust is very good in letting you write maintainable control-flows, like with match.

Often such state machines needs to do some asynchronous stuff, then welcome to async/.await which is a state machine.

It would be easier to help if we can have a more specific example, by the way :v:. For me it's too abstract.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.