Rust
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.
Exercise 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.
Show example solution
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);
}
Test yourself
-
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
Show answer
Everything after it is a positional value, not a flag — This is a POSIX convention, used to handle file names starting with a dash. cargo run -- uses it for the same purpose.
-
Split in two
let (bayraklar, dosyalar): (Vec<&str>, Vec<&str>) =
args.iter().____(|a| a.starts_with("--"));
Show answer
let (bayraklar, dosyalar): (Vec<&str>, Vec<&str>) =
args.iter().partition(|a| a.starts_with("--"));
-
Field type and behaviour
- dosya: String
- Required single value
- dosyalar: Vec<String>
- Zero or more values
- ayrintili: bool
- Valueless flag
- --
- Ends flag parsing
Next lesson: Option flag