In Rust beginner, the reading tracker validated each row, stored an owned title and summed pages. Each check ran once, right where the row was read. This week you build a reading queue, and it has rules that must hold for as long as the program runs. The first one: every book has a positive ID, so later commands such as finish 7 can refer to it. If the ID were a plain u32, every function that receives one would have to check it again, or trust that someone else did.
Rust lets you turn that rule into a type. A newtype is a distinct type that wraps one value. struct BookId(u32) uses tuple-struct syntax: one unnamed field, read as self.0. Put the type in a module and leave the field private, and code outside the module can no longer build a BookId directly. It has to go through the public constructor, and the constructor is where the check lives. Write the check once and every caller is covered.
Predict and run
Which number can become a BookId? How does the caller handle the other one?
mod ids {
pub struct BookId(u32);
impl BookId {
pub fn new(value: u32) -> Option<Self> {
if value == 0 { None } else { Some(Self(value)) }
}
pub fn get(&self) -> u32 {
self.0
}
}
}
fn main() {
for value in [0, 7] {
match ids::BookId::new(value) {
Some(id) => println!("Book #{}", id.get()),
None => println!("ID must be positive"),
}
}
}Check your prediction
ID must be positive
Book #7new returns Option<Self>, so the caller cannot get a BookId without deciding what to do when there is none. The match makes that decision visible. Now add let id = ids::BookId(7); as the first line of main and run again. Predict first: will it compile? Read the error, then remove the line.
The module is the privacy boundary
pub struct BookId(u32); makes the type public but not its field. Privacy in Rust is decided per module, not per type: code inside mod ids can use Self(value) and self.0 freely, while code outside cannot touch the field at all. Both of these fail outside the module:
fn main() {
let id = ids::BookId(7); // build without the check
let raw = ids::BookId::new(7).unwrap();
println!("{}", raw.0); // read the field directly
}The first line reports error[E0603]: tuple struct constructor ... is private, and the second error[E0616]: field 0 of struct BookId is private. That is the point: the only way in is new, and the only way out is get. Writing pub struct BookId(pub u32); would open both doors, and the rule would become a suggestion again.
A type also prevents mix-ups
A newtype helps even where no check is needed. A queue function might take an ID and a page count, and both are numbers. With plain u32 values, swapping the two arguments compiles and silently does the wrong thing. With BookId, the compiler catches it.
mod ids {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BookId(u32);
impl BookId {
pub fn new(value: u32) -> Option<Self> {
if value == 0 { None } else { Some(Self(value)) }
}
}
}
use ids::BookId;
fn log_pages(id: BookId, pages: u32) {
println!("{id:?} read {pages} pages");
}
fn main() {
let Some(id) = BookId::new(7) else {
println!("bad ID");
return;
};
log_pages(id, 30);
log_pages(id, 12);
println!("Same book: {}", BookId::new(7) == Some(id));
}BookId(7) read 30 pages
BookId(7) read 12 pages
Same book: trueCalling log_pages(30, id) instead fails with error[E0308]: mismatched types, because a u32 is not a BookId. Debug output shows the wrapped number, but that is printing, not access: outside code still cannot read id.0.
Two new tools in that example
The example uses two pieces of syntax the beginner course did not. Both appear in almost every lesson from here on.
#[derive(...)] writes standard code for you. A plain u32 can be printed with {:?}, copied and compared, but a new struct can do none of that until it says so. Each of those abilities is a trait, a named set of methods that a type can implement; Day 3 covers traits properly. The #[derive(...)] line above the struct asks the compiler to generate the obvious implementation of each trait listed:
Debugmakes{:?}printBookId(7).Cloneadds.clone().Copygoes further and copies the value on every assignment and call, as with a number, soidcan be passed tolog_pagestwice without moving. ACopytype must also beClone: leaveCloneout and the compiler stops witherror[E0277]: the trait bound BookId: Clone is not satisfied.PartialEqadds==and!=.Eqadds no methods; it promises that every value equals itself, which is true for whole numbers but not for floats (NaN != NaN).EqneedsPartialEqbeside it, or the compiler reportscan't compare `BookId` with `BookId`.
Derive only what a type should support. A BookId has no reason to be added or ordered, so it does not derive those.
let ... else keeps the success case and leaves early otherwise. let Some(id) = BookId::new(7) else { ... }; tries to match the pattern. If it matches, id is bound for the rest of the function. If not, the else block runs, and that block must leave the function, with return, or the loop, with break or continue. It is a shorter way to write this match:
let id = match BookId::new(7) {
Some(id) => id,
None => {
println!("bad ID");
return;
}
};Without the return, the compiler refuses with error[E0308]: `else` clause of `let...else` does not diverge: there would be no id for the following lines to use. Reach for let ... else when the failure case only reports and leaves, and for match when both cases carry on.
Validate at the edge, trust inside
Turn raw input into a checked type as soon as you read it. After that, functions that take a BookId never need to check it again, because no unchecked BookId can exist.
Practice
Your turn
Add a public new to the PageCount newtype in the pages module. It allows 1 to 500 pages inclusive and returns Option<Self>. In main, try 0, 500 and 501, using the getter for the valid one. Print exactly Invalid pages: 0, then Pages: 500, then Invalid pages: 501.
mod pages {
pub struct PageCount(u32);
impl PageCount {
pub fn get(&self) -> u32 {
self.0
}
}
}
fn main() {
// Try constructing 0, 500 and 501.
}Hint 1: the idea
Check the raw number first, and build the wrapper only when the check passes. That way no invalid PageCount ever exists.
Hint 2: a first step
Add pub fn new(value: u32) -> Option<Self> to the impl block. The range 1..=500 has a contains method that takes a reference.
Worked solution
mod pages {
pub struct PageCount(u32);
impl PageCount {
pub fn new(value: u32) -> Option<Self> {
if (1..=500).contains(&value) {
Some(Self(value))
} else {
None
}
}
pub fn get(&self) -> u32 {
self.0
}
}
}
fn main() {
for value in [0, 500, 501] {
match pages::PageCount::new(value) {
Some(count) => println!("Pages: {}", count.get()),
None => println!("Invalid pages: {value}"),
}
}
}Invalid pages: 0
Pages: 500
Invalid pages: 5011..=500 includes both ends, so 500 is the last valid value and 501 the first invalid one. Testing both sides of a boundary is what catches an off-by-one such as 1..500. Because the field is private, a caller cannot skip the check with pages::PageCount(900). The next lesson puts values like these inside enum variants.
Completion is saved in this browser only. It does not measure mastery.