The intermediate reading queue used a private BookId field and a hand-written new function returning Option. That works, but it is a private convention: every type invents its own constructor name and its own way of saying no. A reusable library can expose the same boundary through the standard TryFrom trait instead. Its associated Error type names what a failed conversion returns, and because the field stays private, the try_from implementation is the only way outside code can build the value.
This course builds a stock ledger. Every update must preserve a quantity rule, and a rejected batch must leave the original stock untouched. Start with the smallest value whose validity the API can guarantee: a Quantity. The sample accepts zero stock and caps a quantity at 1000. Once a Quantity exists, no later code needs to check the cap again, because no code outside the module can create one that breaks it.
Predict and run
Which boundary value succeeds? Which conversion returns an error, and what does each line print?
mod domain {
#[derive(Debug, PartialEq, Eq)]
pub struct Quantity(u32);
#[derive(Debug, PartialEq, Eq)]
pub struct TooLarge;
impl TryFrom<u32> for Quantity {
type Error = TooLarge;
fn try_from(value: u32) -> Result<Self, Self::Error> {
if value > 1000 {
Err(TooLarge)
} else {
Ok(Self(value))
}
}
}
impl Quantity {
pub fn get(&self) -> u32 { self.0 }
}
}
fn main() {
println!("{:?}", domain::Quantity::try_from(1000));
println!("{:?}", domain::Quantity::try_from(1001));
}Check your prediction
Ok(Quantity(1000))
Err(TooLarge)The cap is inclusive, so 1000 converts and 1001 does not. Debug prints the wrapped value, but printing is not constructing: outside code can see a Quantity, not make one. Try adding let _quantity = domain::Quantity(1001); as the first line of main and predict what happens. The compiler stops with error[E0603] and says the tuple struct constructor Quantity is private. A tuple struct's name doubles as a constructor function, and that function is only as public as its least public field. Restore the original afterward.
What the standard trait buys you
Implementing TryFrom<u32> for Quantity also gives you TryInto<Quantity> for u32, through a blanket implementation in the standard library. Callers can write value.try_into() and let type inference pick the target, and generic code can accept any type that converts. Because the conversion returns a Result, it also works with ?, as long as the caller's error type can be built from TooLarge.
mod domain {
#[derive(Debug, PartialEq, Eq)]
pub struct Quantity(u32);
#[derive(Debug, PartialEq, Eq)]
pub struct TooLarge;
impl TryFrom<u32> for Quantity {
type Error = TooLarge;
fn try_from(value: u32) -> Result<Self, Self::Error> {
if value > 1000 { Err(TooLarge) } else { Ok(Self(value)) }
}
}
impl Quantity {
pub fn get(&self) -> u32 { self.0 }
}
}
#[derive(Debug)]
enum InputError {
NotANumber,
TooLarge,
}
impl From<domain::TooLarge> for InputError {
fn from(_: domain::TooLarge) -> Self { InputError::TooLarge }
}
fn read_quantity(text: &str) -> Result<domain::Quantity, InputError> {
let raw: u32 = text.trim().parse().map_err(|_| InputError::NotANumber)?;
let quantity = raw.try_into()?;
Ok(quantity)
}
fn main() {
for text in ["12", " 1000 ", "1001", "-3", "many"] {
match read_quantity(text) {
Ok(quantity) => println!("{text:?} -> {}", quantity.get()),
Err(error) => println!("{text:?} -> {error:?}"),
}
}
}"12" -> 12
" 1000 " -> 1000
"1001" -> TooLarge
"-3" -> NotANumber
"many" -> NotANumberTwo stages fail in two different ways. Parsing rejects text that is not an unsigned number, including -3, before the domain rule ever runs. The domain rule then rejects a well-formed number that is too large. The ? after raw.try_into() converts domain::TooLarge into InputError through the From implementation, so the function body stays a straight line. Notice that try_into() needed no type annotation: the function's return type told the compiler the target was Quantity.
The trade-off is flexibility. A type can have only one TryFrom<u32> implementation, with one error type. If you need several differently named constructors from a u32, such as Quantity::at_most(n, cap), an ordinary associated function is the better tool. Use TryFrom when there is one obvious, canonical way to turn the source into the target.
Keep the invariant through every operation
A private field only helps if every method that produces a new Quantity also enforces the rule. An add method that returned Self(self.0 + other.0) would quietly reopen the hole: two valid quantities of 600 would produce 1200. The safe design routes every new value back through the same check.
mod domain {
#[derive(Debug, PartialEq, Eq)]
pub struct Quantity(u32);
#[derive(Debug, PartialEq, Eq)]
pub struct TooLarge;
impl TryFrom<u32> for Quantity {
type Error = TooLarge;
fn try_from(value: u32) -> Result<Self, Self::Error> {
if value > 1000 { Err(TooLarge) } else { Ok(Self(value)) }
}
}
impl Quantity {
pub fn get(&self) -> u32 { self.0 }
pub fn plus(&self, other: &Quantity) -> Result<Quantity, TooLarge> {
Quantity::try_from(self.0 + other.0)
}
}
}
fn main() {
let small = domain::Quantity::try_from(400).unwrap();
let large = domain::Quantity::try_from(600).unwrap();
println!("{:?}", small.plus(&large));
println!("{:?}", large.plus(&large));
}Ok(Quantity(1000))
Err(TooLarge)Because both inputs are at most 1000, their sum is at most 2000 and cannot overflow u32, so plain + is safe here. That reasoning depends on the invariant itself, which is exactly the kind of fact a validated type lets you rely on. On Day 4 you will handle signed changes, where overflow becomes a real risk.
Audit the module, not the callers
With a private field, the only code that can break the rule lives inside mod domain. When you review a validated type, read every function in that module that writes Self(...) or changes self.0. If each one checks the rule, every caller is safe, however many there are.
Practice
Your turn
Build a BatchId newtype with a private field, implementing TryFrom<u32> with a ZeroId error. Zero must fail and 1 must succeed. Add a get method. In main, assert that BatchId::try_from(0) is Err(ZeroId), that 1 converts and get() returns 1, and that 7u32.try_into() produces an ID whose get() is 7. Then print ID checks passed.
fn main() {
// Define the domain module above main and exercise its conversion.
}Hint 1: the idea
The associated error type belongs to the conversion: write type Error = ZeroId; inside the impl TryFrom<u32> for BatchId block. You get try_into for free once try_from exists.
Hint 2: a first step
Put the wrapper in a module with pub struct BatchId(u32); so the field stays private. Derive Debug, PartialEq, Eq on both BatchId and ZeroId so assert_eq! can compare and print them.
Worked solution
mod domain {
#[derive(Debug, PartialEq, Eq)]
pub struct BatchId(u32);
#[derive(Debug, PartialEq, Eq)]
pub struct ZeroId;
impl TryFrom<u32> for BatchId {
type Error = ZeroId;
fn try_from(value: u32) -> Result<Self, Self::Error> {
if value == 0 { Err(ZeroId) } else { Ok(Self(value)) }
}
}
impl BatchId {
pub fn get(&self) -> u32 { self.0 }
}
}
fn main() {
assert_eq!(domain::BatchId::try_from(0), Err(domain::ZeroId));
let id = domain::BatchId::try_from(1).expect("valid ID");
assert_eq!(id.get(), 1);
let other: Result<domain::BatchId, _> = 7u32.try_into();
assert_eq!(other.map(|id| id.get()), Ok(7));
println!("ID checks passed");
}ID checks passedThe 7u32.try_into() line needs no extra code, because the standard library derives TryInto from your TryFrom. The u32 suffix matters: a bare 7 could be any integer type, and only u32 has a conversion into BatchId. A successful conversion is the single point where a raw integer becomes an ID callers can trust. In the next lesson, the error itself will carry the rejected value.
Completion is saved in this browser only. It does not measure mastery.