Rust
Option flag
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}"))
}
}
}
Exercise Optional port
Write the port_oku function above. Print the results for ["-p", "8080"] and an empty argument list with {:?}, separated by a space.
Show example 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);
}
Test yourself
-
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
- No difference
Show answer
With Option the "not given" information is kept; with a default it's lost — If it matters whether the user gave the value explicitly, use Option.
-
Optional field
#[arg(short, long)]
port: ____,
Show answer
#[arg(short, long)]
port: Option<u16>,
-
Command line and port
- -p 8080
- Some(8080)
- --port 9000
- Some(9000)
- (none)
- None
- -p abc
- Error
Next lesson: Subcommand