Option flag
- Rust course
- Intermediate
- Lesson 98/115
- 4 min
Define options and bool flags with --flag.
Optional flags
If the field type is Option<T>, the argument is optional; if it isn't given, it's None. This makes it easy to build "if the user didn't say, look elsewhere" logic:
#[derive(Parser)]
struct Args {
/// Dinlenecek port
#[arg(short, long)]
port: Option<u16>,
}
let port = args.port
.or_else(|| std::env::var("PORT").ok()?.parse().ok())
.unwrap_or(8080);The usual order: command line → environment variable → config file → default.
Short and long forms
clap accepts -p 8080, --port 8080 and --port=8080 alike. When writing by hand, you need to search for both names:
fn port_oku(args: &[&str]) -> Result<Option<u16>, String> {
match args.iter().position(|a| *a == "-p" || *a == "--port") {
None => Ok(None),
Some(i) => {
let s = args.get(i + 1).ok_or("--port için değer eksik")?;
s.parse().map(Some).map_err(|_| format!("geçersiz port: {s}"))
}
}
}Practice Optional port
Write the port_oku function above. Print the results for ["-p", "8080"] and an empty argument list with {:?}, separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn port_oku(args: &[&str]) -> Result<Option<u16>, String> {
match args.iter().position(|a| *a == "-p" || *a == "--port") {
None => Ok(None),
Some(i) => {
let s = args.get(i + 1).ok_or("--port için değer eksik")?;
s.parse().map(Some).map_err(|_| format!("geçersiz port: {s}"))
}
}
}
fn main() {
let a = port_oku(&["-p", "8080"]).unwrap();
let b = port_oku(&[]).unwrap();
println!("{:?} {:?}", a, b);
}Expected output
Some(8080) None
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the difference between <code>Option<u16></code> and <code>default_value_t</code>?
- Option makes it required
- default_value_t doesn't compile
- With Option the "not given" information is kept; with a default it's lost Correct answer
- No difference
Explanation: If it matters whether the user gave the value explicitly, use Option.
2 Optional field
#[arg(short, long)]
port: ____,
#[arg(short, long)]
port: Option<u16>,
Explanation: An Option<T> type makes the argument optional.
3 Command line and port
| Term | Meaning |
|---|---|
-p 8080 |
Some(8080) |
--port 9000 |
Some(9000) |
(none) |
None |
-p abc |
Error |