Enforce Order State Transitions with Enums
Model order status as an enum and allow only the transitions place, pay, ship, and cancel from valid states.
Code
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OrderState {
Draft,
Placed,
Paid,
Shipped,
Cancelled,
}
#[derive(Debug, PartialEq, Eq)]
enum TransitionError {
InvalidTransition {
from: OrderState,
event: &'static str,
},
}
struct Order {
state: OrderState,
}
impl Order {
fn new() -> Self {
Self {
state: OrderState::Draft,
}
}
fn apply(&mut self, event: &'static str) -> Result<OrderState, TransitionError> {
use OrderState::*;
let next = match (self.state, event) {
(Draft, "place") => Placed,
(Placed, "pay") => Paid,
(Paid, "ship") => Shipped,
(Draft | Placed, "cancel") => Cancelled,
(_, _) => {
return Err(TransitionError::InvalidTransition {
from: self.state,
event,
});
}
};
self.state = next;
Ok(next)
}
}
fn main() {
let mut order = Order::new();
assert_eq!(
order.apply("pay"),
Err(TransitionError::InvalidTransition {
from: OrderState::Draft,
event: "pay",
})
);
assert_eq!(order.apply("place"), Ok(OrderState::Placed));
assert_eq!(order.apply("pay"), Ok(OrderState::Paid));
assert_eq!(
order.apply("cancel"),
Err(TransitionError::InvalidTransition {
from: OrderState::Paid,
event: "cancel",
})
);
assert_eq!(order.apply("ship"), Ok(OrderState::Shipped));
assert_eq!(
order.apply("ship"),
Err(TransitionError::InvalidTransition {
from: OrderState::Shipped,
event: "ship",
})
);
println!("final state: {:?}", order.state);
}
What the code does
Count the functions new, apply and main as the entire surface area of Enforce Order State Transitions with Enums.
The Result return type makes both outcomes part of the signature. match here is the control flow: arms enumerate the value’s shapes exhaustively.
Points of care
- Adapting this code means honoring its
Resultcontract: match each one or pass it up with?.
Applying it
The main signature reads fn new() -> Self
Running the file prints labeled results such as final state: — each operation’s effect is visible in the output.
Treat main as the orchestrator calling new and apply in a fixed order.
Statements that matter
return Err(TransitionError::InvalidTransition {
from: self.state,
event,
});
assert_eq!(order.apply("place"), Ok(OrderState::Placed));
assert_eq!(order.apply("ship"), Ok(OrderState::Shipped));
Interactive Tools for This Topic
FAQ
- How are errors reported?
- Through the type system: failures are `Result` variants the caller must consume.
- What does Enforce Order State Transitions with Enums print when run?
- Execute the whole file; each printed line is prefixed with a label like `final state:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.