CodeBlanks Logo Icon CodeBlanks

Positional argument

Define positional arguments.

Positional arguments

Arguments without a flag in front are positional; they are assigned to fields in order. A positional field of type Vec collects all remaining values:

#[derive(Parser)]
struct Args {
    /// İşlenecek dosyalar
    dosyalar: Vec<String>,

    /// Ayrıntılı çıktı
    #[arg(short, long)]
    ayrintili: bool,
}
// $ say a.txt --ayrintili b.txt
// dosyalar = ["a.txt", "b.txt"], ayrintili = true

bool fields are flags that take no value: true if present, false otherwise.

Separating by hand

partition can be used to separate flags from positional values:

let (bayraklar, dosyalar): (Vec<&str>, Vec<&str>) =
    args.iter().partition(|a| a.starts_with("--"));
let ayrintili = bayraklar.contains(&"--ayrintili");

partition splits an iterator into two collections by a condition, in a single pass.

Practice Files and a flag

Separate the arguments ["a.txt", "--ayrintili", "b.txt"] into flags and files with partition. Print the file list with {:?} and whether the --ayrintili flag is present, separated by a space.

Starter code

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

Sample solution

main.rs
fn main() {
    let args = ["a.txt", "--ayrintili", "b.txt"];
    let (bayraklar, dosyalar): (Vec<&str>, Vec<&str>) = args.iter().partition(|a| a.starts_with("--"));
    let ayrintili = bayraklar.contains(&"--ayrintili");
    println!("{:?} {}", dosyalar, ayrintili);
}

Expected output

["a.txt", "b.txt"] true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the <code>--</code> argument mean? (<code>say -- --garip-ad.txt</code>)

  • It starts a comment
  • It turns off all flags
  • It errors
  • Everything after it is a positional value, not a flag Correct answer

Explanation: This is a POSIX convention, used to handle file names starting with a dash. cargo run -- uses it for the same purpose.

2 Split in two

Question
let (bayraklar, dosyalar): (Vec<&str>, Vec<&str>) =
    args.iter().____(|a| a.starts_with("--"));
Answer
let (bayraklar, dosyalar): (Vec<&str>, Vec<&str>) =
    args.iter().partition(|a| a.starts_with("--"));

Explanation: partition puts the matching and non-matching items into separate collections.

3 Field type and behaviour

Term Meaning
dosya: String Required single value
dosyalar: Vec<String> Zero or more values
ayrintili: bool Valueless flag
-- Ends flag parsing

All lessons in Intermediate