-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path05-split-transition.rs
More file actions
47 lines (38 loc) · 1.12 KB
/
05-split-transition.rs
File metadata and controls
47 lines (38 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use statum::{machine, state, transition};
#[state]
#[derive(Clone)]
enum CheckoutState {
Cart,
PaymentPending(String),
PaymentConfirmed,
Shipped,
}
#[machine]
#[derive(Clone)]
struct OrderMachine<CheckoutState> {
user_id: u64,
}
#[transition]
impl OrderMachine<Cart> {
pub fn proceed_to_payment(self) -> OrderMachine<PaymentPending> {
self.transition_with("txn_123".to_string())
}
}
#[transition]
impl OrderMachine<PaymentPending> {
pub fn confirm_payment(self) -> OrderMachine<PaymentConfirmed> {
self.transition()
}
pub fn cancel_payment(self) -> OrderMachine<Cart> {
self.transition()
}
}
pub fn run() {
let cart_machine = OrderMachine::<Cart>::builder().user_id(123).build();
// 🔥 Works! Rust infers that `transition_with<String>()` should be called.
let pending = cart_machine.proceed_to_payment();
// 🔥 Works! Rust selects the correct `transition()` implementation.
let _confirmed = pending.clone().confirm_payment();
//// 🔥 Works! PaymentPending -> Cart also compiles fine.
let _back_to_cart = pending.cancel_payment();
}