Day 4 – Rust Enums and Cargo
Today's Focus
Deepen Rust knowledge with enums, pattern matching, and Cargo dependency management.
Tasks
- Refactor your Rust CLI to use
clapfor argument parsing:cargo add clap --features derive. Use the derive macro to define a struct with#[derive(Parser)]and subcommands forcountandtop. Read the generated help text with--help. - Implement a custom error type using an
enum MyError { IoError(std::io::Error), ParseError(String) }and implementstd::fmt::Displayfor it. ReplaceBox<dyn Error>withMyErrorin your function signatures. - Use
matchexhaustively on yourMyErrorenum inmain()to print a different message for each variant. Add a new variant and confirm the compiler forces you to handle it everywhere. - Explore Rust's
Option<T>: rewrite a function that previously returned a sentinel value (e.g.""for "not found") to returnOption<&str>. Call it with.unwrap_or("default"),.map(|s| s.to_uppercase()), andif let Some(v) = result { ... }. - Inspect
Cargo.tomlandCargo.lock: add a dependency with a feature flag (e.g.serdewithfeatures = ["derive"]) and one markedoptional = true. Understand the difference betweenCargo.lock(committed in binaries) and when to omit it (libraries). - Run
cargo audit(install withcargo install cargo-audit) to check your dependencies. Investigate any advisory reported.
Reading / Reference
- The Rust Book — Chapters 10 (Generics), 6 (Enums and Pattern Matching), 9 (Error Handling).
- Cargo Book — Specifying Dependencies and Features sections.
- clap documentation — Derive tutorial.