Home
Rust
env args Example (Command-Line Flags)
This page was last reviewed on Nov 21, 2024.
Dot Net Perls
Env args. A Rust program can accept command-line arguments. Suppose we want to pass a simple argument to a program like a folder name.
With env args, a method in std, we can loop over the arguments to a program. The first argument is the name of the program itself.
PathBuf
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.
for
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.
parse
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 21, 2024 (edit link).
Home
Changes
© 2007-2024 Sam Allen.