Example program. In this simple example, we try to detect a "folder" argument to the program. Then, the next string in the arguments is the folder name itself.
Part 1 We use a for-loop to iterate over the arguments to the program. This skips over the first argument.
Part 2 When the "folder" flag is detected, we set the folder_next variable to true.
Part 3 When we are on the string after the "folder" flag, we use the string as the folder name.
use std::env;
fn main() {
let mut folder_next = false;
let mut folder = String::new();
// Part 1: loop over arguments.
for argument in env::args() {
// ... Display arguments.
println!("Argument: {}", argument);
// Part 2: use flag after "-folder" was detected to set argument.
if folder_next {
folder = argument;
folder_next = false;
continue;
}
// Part 3: if "-folder" detected, set flag bool.
if argument == "-folder" {
folder_next = true;
continue;
}
}
// Result.
println!("Folder argument: {}", folder)
}.hello-rust -folder ~/temp/&Argument: ./hello-rust
Argument: -folder
Argument: /Users/sam/temp/
Folder argument: /Users/sam/temp/
String new, notes. If we use the empty string literal (which is a str reference) as the folder local, we will get a compiler error. This is the "mismatched types" error in Rust.
Note Rust says we should "consider borrowing here" if we do not use String::new for the folder variable.
Tip In Rust, using String objects instead of str references is often a good solution to borrowing problems.
Summary. We developed a simple command-line flag argument parser in Rust. This code could be adapted to consider more arguments, and even provide parsing of types.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 21, 2024 (edit link).