One clean split
Use Option for absence. Use Result for failure.
If nothing went wrong but a value may not exist, choose Option. If something tried to happen and can fail, choose Result.
Why this matters
A CLI always meets messy input. A user may skip an argument. A file path may be wrong. A number may not parse.
Rust makes you handle these cases before your project reaches the demo table. That is good. Your tool should print a clear message, not crash with a confusing panic.
Option for missing input
Here is a tiny CLI pattern using std::env::args. The first real argument may be missing, so nth(1) returns Option.
match forces you to handle both cases.
use std::env;
fn main() {
let name = env::args().nth(1);
match name {
Some(value) => println!("Hello, {value}"),
None => println!("Usage: cargo run -- <name>"),
}
}Result for failure
Reading a file can fail. The file may not exist, or your program may not have permission.
Return Result from a function, then use ? to pass the error upward instead of writing a match every time.
use std::fs;
use std::error::Error;
fn read_notes(path: &str) -> Result<String, Box<dyn Error>> {
let content = fs::read_to_string(path)?;
Ok(content)
}
fn main() -> Result<(), Box<dyn Error>> {
let content = read_notes("notes.txt")?;
println!("{content}");
Ok(())
}Avoid panic habits
Beginners often use unwrap() because it makes the compiler quiet. It also makes your CLI crash when input is missing or invalid.
For a hackathon demo, unwrap() is risky. Use match for a friendly message, or return Result and use ? for real failures.
Ask AI carefully
If you use ChatGPT or Gemini, ask for code that avoids unwrap() and returns Result from main. Then check the answer yourself.
Look for three things: Option is matched, fallible work returns Result, and ? is only used inside a function that returns Result or Option.
Prompt:
Convert this Rust CLI code to handle missing arguments and file read errors without unwrap(). Use Option, Result, match, and ? where suitable.Pick the type
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done