bhylu.com

Advertisements

Rust Exercises

Practise checked arithmetic and failed lookups without hiding errors.

How it works

Before running the source, predict what should happen when a tray count is multiplied safely and when a collection index does not exist. The exercise combines a numerical boundary and an absence boundary so neither is mistaken for a normal zero. Explain whether the caller should retry, reject input or show an empty-state message rather than automatically panicking.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

exercises.rs

fn main() {
    fn batches(trays: u32) -> Result<u32, &'static str> { trays.checked_mul(3).ok_or("overflow") }
    assert_eq!(batches(4), Ok(12));
    assert_eq!(batches(u32::MAX), Err("overflow"));
    let counts = [3,5,8];
    assert_eq!(counts.get(99),None);
    println!("Valid batch 12; overflow error and absent index remain distinct");
}

Expected result

Valid batch 12; overflow error and absent index remain distinct

The multiplication converts Option into a Result with a clear error label. The lookup remains Option because absence is all the caller needs to know in this fixture. As a further exercise, change the project grammar to accept a new area format and update both acceptance and refusal tests before changing the implementation.

Primary technical reference: Rust documentation.