CodeBlanks Logo Icon CodeBlanks

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}"))
        }
    }
}

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

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
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&lt;u16&gt;</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

Question
#[arg(short, long)]
port: ____,
Answer
#[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

All lessons in Intermediate