This checkpoint combines today's ideas in one small type. A reading target says how many pages you plan to read this week, and it remembers how many you have logged so far. Two rules must always hold: the target is positive, and the logged count never exceeds it. You will enforce the first in a constructor and the second in a method, and keep both fields private so no other code can break them.
What you will use
- A private field behind a module.
Targetlives inmod targetswith privatelimitandloggedfields, so outside code must use your constructor and methods. - A checked constructor.
new(limit)returnsOption<Self>, withNonefor a zero target and a count that starts at zero. - A
&mut selfmethod that can reject.log(pages)returnsResult<(), LogError>, and a rejected call leaves the count unchanged. - Derived
Debug,PartialEqandEq. They letassert_eq!compare results such asErr(LogError::BeyondTarget).
Plan before you type
- Inside the module, add
impl Targetwithpub fn new(limit: u32) -> Option<Self>. - Add
pub fn logged(&self) -> u32somaincan read the count without touching the field. - Write
pub fn log(&mut self, pages: u32) -> Result<(), LogError>. Work out the remaining pages first and reject anything larger, before changinglogged. - In
main, check thatnew(0)isNone, then build a target of 10 and log 3, 8 and 7, asserting each result and the count after it. - Finish with the boundary: once the target is full, logging even 1 more page must fail.
Prove the checks can fail
Break your method on purpose and run again. Change the test to pages >= remaining and the exact log of 7 must fail an assertion. Move self.logged += pages; above the check and the count assertion after the rejected 8 must fail. If an assertion still passes with a broken method, it is not testing anything.
Mistakes worth checking for
- The run aborts with "attempt to add with overflow" for a huge page count: the check computed
self.logged + pages, which can overflow au32. Subtract instead:self.limit - self.loggedcannot go below zero because the invariant keepsloggedat or belowlimit. - Logging exactly the remaining pages is rejected: the comparison uses
>=where>is meant. - After a rejection, the count has changed: the method updated
loggedbefore deciding. mainfails with "fieldloggedof structTargetis private": read the count through the getter, not the field.
Your turn
Write the constructor, log and the logged getter. In main, check that a zero target cannot be built. For a target of 10: logging 3 succeeds, 8 fails with BeyondTarget and the count stays 3, 7 succeeds and the count becomes 10, and a further 1 fails. Print Target checks passed at the end.
mod targets {
#[derive(Debug, PartialEq, Eq)]
pub enum LogError {
BeyondTarget,
}
pub struct Target {
limit: u32,
logged: u32,
}
}
fn main() {
// Construct a target and test both branches of your method.
}Hint 1: the idea
Compare against the remaining amount before adding. This also avoids overflow if the caller supplies a very large page count.
Hint 2: a first step
Inside the module, add impl Target with a constructor returning Option<Self>, built as Self { limit, logged: 0 }, and a getter returning self.logged.
Worked solution
mod targets {
#[derive(Debug, PartialEq, Eq)]
pub enum LogError {
BeyondTarget,
}
pub struct Target {
limit: u32,
logged: u32,
}
impl Target {
pub fn new(limit: u32) -> Option<Self> {
if limit == 0 { None } else { Some(Self { limit, logged: 0 }) }
}
pub fn log(&mut self, pages: u32) -> Result<(), LogError> {
if pages > self.limit - self.logged {
return Err(LogError::BeyondTarget);
}
self.logged += pages;
Ok(())
}
pub fn logged(&self) -> u32 {
self.logged
}
}
}
fn main() {
assert!(targets::Target::new(0).is_none());
let Some(mut target) = targets::Target::new(10) else {
panic!("positive target should work");
};
assert_eq!(target.log(3), Ok(()));
assert_eq!(target.log(8), Err(targets::LogError::BeyondTarget));
assert_eq!(target.logged(), 3);
assert_eq!(target.log(7), Ok(()));
assert_eq!(target.logged(), 10);
assert_eq!(target.log(1), Err(targets::LogError::BeyondTarget));
assert_eq!(target.log(u32::MAX), Err(targets::LogError::BeyondTarget));
println!("Target checks passed");
}Target checks passedlet Some(...) = ... else extracts a valid target or takes the failure branch, which here would mean the constructor broke a test assumption. The u32::MAX line proves the subtraction-based check cannot overflow. Every rejection leaves logged within limit, so the invariant set by the constructor holds after any sequence of calls. Day 2 turns to borrowing: reading parts of data without copying or owning it.
Completion is saved in this browser only. It does not measure mastery.