Practice Projects
Each project adds one twist. Use only the standard library.
1. Word ledger
Read text from command-line arguments and print each distinct word with its count.
Constraints:
- Normalize words with
to_lowercase. - Use
HashMap<String, usize>. - Do not clone a word after inserting it.
- Return a useful error when no text is supplied.
Evidence to collect:
$ cargo run -- one fish two fish
fish: 2
one: 1
two: 1
Sort before printing so output is deterministic.
2. Command parser
Parse these commands into an enum:
add <left> <right>
echo <text>
quit
Constraints:
- Parsing returns
Result<Command, String>. - Execution uses an exhaustive
match. - Bad integers and wrong argument counts produce different messages.
Write one test containing a successful command and one rejected command.
3. Shared counter
Spawn four threads. Each increments one shared counter 1,000 times.
Constraints:
- Use
Arc<Mutex<usize>>. - Join every thread.
- Explain why
Rc<RefCell<usize>>is rejected. - The final assertion is
4_000.
4. Borrow-first refactor
Take a program that accepts String parameters and returns cloned strings. Change inputs to &str wherever ownership is unnecessary.
Keep owned return values only when the result is newly constructed or must outlive all inputs. Use compiler errors to justify each remaining String.
Completion check
A project is done when:
cargo fmt --check
cargo clippy --all-targets -- -D warnings
cargo test
passes and you can answer:
- Who owns each heap allocation?
- Which functions borrow rather than own?
- Which invalid states are represented by the type system?
- Which failures are returned as
Result?