A Quantity is valid on its own. A stock change is different: it is assembled from several inputs, perhaps edited along the way, and only then checked as a whole. The usual approach is a struct with a validated: bool flag, but a flag is only a promise. Nothing stops code from changing a field after the check, or from forgetting to look at the flag at all.
The type-state pattern gives each stage its own type instead. A Draft has public fields you can edit freely. A Checked has private fields and read-only access, so the only way to get one is through validation. Validation takes self by value: a successful call consumes the draft and moves its contents into the checked value. An operation that accepts &Checked can rely on validation having run, and the compiler prevents anyone from editing or reusing the draft afterward. The ledger uses this shape to hand a checked batch from the parser to the code that applies it.
Predict and run
What can be passed to apply? Which value owns the delta after validation?
mod batches {
pub struct Draft { pub delta: i64 }
pub struct Checked { delta: i64 }
impl Draft {
pub fn validate(self) -> Result<Checked, &'static str> {
if self.delta == 0 {
Err("zero delta")
} else {
Ok(Checked { delta: self.delta })
}
}
}
impl Checked {
pub fn delta(&self) -> i64 { self.delta }
}
}
fn apply(batch: &batches::Checked) {
println!("Apply {}", batch.delta());
}
fn main() {
let draft = batches::Draft { delta: 5 };
let checked = draft.validate().expect("nonzero");
apply(&checked);
}Check your prediction
Apply 5Only a &Checked fits apply, and after validate the checked value owns the delta. Try two changes, one at a time, and predict each diagnostic before you run it. First, replace apply(&checked); with apply(&batches::Draft { delta: 5 });. The compiler reports error[E0308]: mismatched types, expected &Checked. Second, restore that line and add println!("{}", draft.delta); after it. Now you get error[E0382]: borrow of moved value for draft, with a note that validate takes ownership of the receiver. Both mistakes are caught before the program runs. Restore the original when you are done.
Why a boolean check is not enough
Compare the same rule written as a method that only reports. The check runs and passes, then the caller edits the draft, and the edited value still reaches the code that applies it.
struct Draft { delta: i64 }
impl Draft {
fn is_valid(&self) -> bool { self.delta != 0 }
}
fn apply(batch: &Draft) {
println!("Apply {}", batch.delta);
}
fn main() {
let mut draft = Draft { delta: 5 };
if draft.is_valid() {
draft.delta = 0;
apply(&draft);
}
}Apply 0The bool describes the draft at one moment and is forgotten immediately. With type state, the result of the check is a value that carries the guarantee forward: Checked has no public fields and no setters, so it cannot drift from what was validated. That is the design reason to make validation consume the draft rather than borrow it. A validate(&self) -> Result<Checked, _> that copied the fields would also work, but it would leave a live, editable draft beside the checked value and invite code to use the wrong one.
Give the draft back on failure
Consuming self has a cost on the failure path. In the first example a rejected draft is simply dropped, so a caller who wants to fix one field and try again must rebuild the whole thing. When drafts are expensive to assemble, return the draft inside the error.
mod batches {
#[derive(Debug)]
pub struct Draft { pub item: String, pub delta: i64 }
pub struct Checked { item: String, delta: i64 }
pub struct Rejected { pub draft: Draft, pub reason: &'static str }
impl Draft {
pub fn validate(self) -> Result<Checked, Rejected> {
if self.delta == 0 {
return Err(Rejected { draft: self, reason: "zero delta" });
}
Ok(Checked { item: self.item, delta: self.delta })
}
}
impl Checked {
pub fn describe(&self) -> String { format!("{} {:+}", self.item, self.delta) }
}
}
fn main() {
let draft = batches::Draft { item: String::from("bolt"), delta: 0 };
let checked = match draft.validate() {
Ok(checked) => checked,
Err(rejected) => {
println!("Rejected {:?}: {}", rejected.draft, rejected.reason);
let mut draft = rejected.draft;
draft.delta = 3;
draft.validate().ok().expect("fixed draft")
}
};
println!("Apply {}", checked.describe());
}Rejected Draft { item: "bolt", delta: 0 }: zero delta
Apply bolt +3The String inside the draft was never cloned: it moved into the error, back into a new draft binding and finally into Checked. The {:+} format prints the sign of a number, which suits a stock change. Note the .ok() before expect: Result::expect needs a Debug error type, and Rejected does not derive one, so the code converts to an Option first. The trade-off is a slightly heavier error type. The standard library makes the same choice in places such as String::from_utf8, whose error can hand back the original bytes.
When type state is worth it
Use separate types when a value crosses a boundary in a known state, such as from parsing to applying, and several functions downstream depend on that state. For a check used once, right next to the code that relies on it, an ordinary Result is simpler.
Practice
Your turn
Extend validate to also reject changes whose absolute value is over 100. Test the deltas -101, -100, 0, 100 and 101 and print accepted or rejected for each, in that order. Also confirm that i64::MIN is rejected without overflowing.
mod batches {
pub struct Draft { pub delta: i64 }
pub struct Checked { delta: i64 }
impl Draft {
pub fn validate(self) -> Result<Checked, &'static str> {
if self.delta == 0 {
Err("zero delta")
} else {
Ok(Checked { delta: self.delta })
}
}
}
impl Checked {
pub fn delta(&self) -> i64 { self.delta }
}
}
fn main() {
// Construct a draft for each boundary and inspect whether validation succeeds.
}Hint 1: the idea
self.delta.abs() overflows for i64::MIN, because +9223372036854775808 does not fit in i64; with overflow checks on, that is a panic. Comparing against both signed endpoints avoids computing the absolute value at all.
Hint 2: a first step
Replace the check that calls abs() with one that compares self.delta against the two allowed endpoints directly, before Checked is built. An inclusive range has a method that does exactly that comparison.
Worked solution
mod batches {
pub struct Draft { pub delta: i64 }
pub struct Checked { delta: i64 }
impl Draft {
pub fn validate(self) -> Result<Checked, &'static str> {
if self.delta == 0 || !(-100..=100).contains(&self.delta) {
Err("delta must be nonzero and within -100..=100")
} else {
Ok(Checked { delta: self.delta })
}
}
}
impl Checked {
pub fn delta(&self) -> i64 { self.delta }
}
}
fn main() {
for delta in [-101, -100, 0, 100, 101] {
let outcome = match (batches::Draft { delta }).validate() {
Ok(checked) => format!("accepted {}", checked.delta()),
Err(_) => String::from("rejected"),
};
println!("{delta}: {outcome}");
}
assert!(batches::Draft { delta: i64::MIN }.validate().is_err());
println!("i64::MIN: rejected");
}-101: rejected
-100: accepted -100
0: rejected
100: accepted 100
101: rejected
i64::MIN: rejectedThe parentheses around batches::Draft { delta } are needed because a struct literal cannot appear directly as the scrutinee of a match. Both endpoints are accepted and both values one step beyond are rejected, which is the minimum set of tests for an inclusive range. A Checked can only exist once both rules pass, so apply never needs to repeat them.
Completion is saved in this browser only. It does not measure mastery.