This checkpoint combines the day's three ideas in one small type. A transfer moves an amount of stock from one location to another. Each field can be wrong on its own, a zero ID or a zero amount, but one rule involves two fields at once: the source and the destination must differ. A rule like that cannot live in a validated field type such as Quantity, because neither field knows about the other. It belongs at the point where the whole value is checked, and the result should be a type that downstream code can trust without repeating the checks.
What you will use
- A draft and a checked type.
Drafthas public fields for assembling input.Checkedhas private fields and is only produced byDraft::validate(self). - An error enum with context.
TransferErrorhas one variant per broken rule, carrying the offending value where there is one, and aDisplaymessage for each. - The
Errortrait. Implementstd::error::Errorso the error fits standard interfaces. - A read-only consumer. A
summarymethod onCheckedis the only way the rest of the program sees the fields.
Plan before you type
- Put
Draft,CheckedandTransferErrorin atransfersmodule, withChecked's fields private. - Give
TransferErrorthe variantsZeroId,SameLocation(u32)andZeroAmount, and deriveDebug, PartialEq, Eq. - Implement
Displaywith amatch, producinglocation IDs must be positive,cannot transfer from 4 to itselfandamount must be positive. - Write
validate(self) -> Result<Checked, TransferError>, checking zero IDs first, then the shared rule, then the amount. - In
main, run one draft per rejected condition, assert the exact variant and print each message. Add two drafts that break two rules at once, to pin the order. Then validate one good draft and print its summary.
Prove each rule is checked
A draft that breaks exactly one rule, with every other field valid, proves that particular check exists: if a draft broke two rules, deleting one check would go unnoticed because the other would still reject it. But single-defect drafts cannot see the order of the checks. With one rule broken, every order gives the same answer. Order shows only when two rules are broken at once and the exact variant is asserted: (4, 4, 0) must report the same location, not the zero amount, and (0, 0, 5) must report the zero ID, not "from 0 to itself". Use one-defect drafts to prove each check exists, and a deliberate two-defect draft for each ordering you promise.
Mistakes worth checking for
(4, 4, 0)reports a zero amount instead of the same location: the checks run in a different order than planned, so decide the order deliberately and test it.applyorsummarycan be called on aDraft: the consumer accepts the draft type, orCheckedhas public fields that let outside code build one.- The compiler rejects
impl std::error::Error for TransferError {}withE0277:DisplayorDebugis missing. unwrap_err()does not compile on the result: it prints theOkvalue if it panics, so it needsCheckedto implementDebug. Call.err()to get anOptionof the error instead, or deriveDebugonCheckedif showing its fields is acceptable.
Your turn
Write the transfers module as planned. Check the one-defect drafts (0, 2, 5), (1, 0, 5), (4, 4, 5) and (1, 2, 0) as source, destination and amount, then the two-defect drafts (0, 0, 5) and (4, 4, 0), asserting each variant and printing each error message. Then validate (1, 2, 5) and print its summary as 1 -> 2: 5.
fn main() {
// Define Draft, Checked and TransferError inside a module, then check their boundary.
}Hint 1: the idea
Validate the relationship between fields as well as each field. The same-location rule only makes sense once both IDs are known to be positive, so check it after the zero-ID rule.
Hint 2: a first step
Write the error enum and its Display first, and print one variant to see the message. Then start validate with the zero-ID rule as an early return; the fields move into Checked only after every check has passed.
Worked solution
mod transfers {
use std::fmt;
pub struct Draft { pub from: u32, pub to: u32, pub amount: u32 }
pub struct Checked { from: u32, to: u32, amount: u32 }
#[derive(Debug, PartialEq, Eq)]
pub enum TransferError {
ZeroId,
SameLocation(u32),
ZeroAmount,
}
impl fmt::Display for TransferError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TransferError::ZeroId => write!(f, "location IDs must be positive"),
TransferError::SameLocation(id) => write!(f, "cannot transfer from {id} to itself"),
TransferError::ZeroAmount => write!(f, "amount must be positive"),
}
}
}
impl std::error::Error for TransferError {}
impl Draft {
pub fn validate(self) -> Result<Checked, TransferError> {
if self.from == 0 || self.to == 0 { return Err(TransferError::ZeroId); }
if self.from == self.to { return Err(TransferError::SameLocation(self.from)); }
if self.amount == 0 { return Err(TransferError::ZeroAmount); }
Ok(Checked { from: self.from, to: self.to, amount: self.amount })
}
}
impl Checked {
pub fn summary(&self) -> String {
format!("{} -> {}: {}", self.from, self.to, self.amount)
}
}
}
use transfers::{Draft, TransferError};
fn main() {
let rejected = [
((0, 2, 5), TransferError::ZeroId),
((1, 0, 5), TransferError::ZeroId),
((4, 4, 5), TransferError::SameLocation(4)),
((1, 2, 0), TransferError::ZeroAmount),
// Two rules broken at once: these pin the order of the checks.
((0, 0, 5), TransferError::ZeroId),
((4, 4, 0), TransferError::SameLocation(4)),
];
for ((from, to, amount), expected) in rejected {
let error = Draft { from, to, amount }.validate().err().expect("rejected");
assert_eq!(error, expected);
println!("({from}, {to}, {amount}): {error}");
}
let transfer = Draft { from: 1, to: 2, amount: 5 }.validate().unwrap();
println!("{}", transfer.summary());
}(0, 2, 5): location IDs must be positive
(1, 0, 5): location IDs must be positive
(4, 4, 5): cannot transfer from 4 to itself
(1, 2, 0): amount must be positive
(0, 0, 5): location IDs must be positive
(4, 4, 0): cannot transfer from 4 to itself
1 -> 2: 5The first four drafts each break one rule, so deleting any check makes its assertion fail. The last two break two rules each, so they are the ones that fail if the checks are reordered: move the amount check first and (4, 4, 0) reports ZeroAmount; move the same-location check first and (0, 0, 5) reports SameLocation(0). Without them, every order of the three ifs would print the same output. .err().expect(...) keeps Checked free of a Debug derive, which would otherwise be the only reason to add one. Notice that SameLocation(4) carries the ID, so the message can name it. On Day 4 a checked batch like this one is applied atomically to the ledger.
Completion is saved in this browser only. It does not measure mastery.