env args Example (Command-Line Flags)
This page was last reviewed on Dec 17, 2021.
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.
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.
Detail We use a for-loop to iterate over the arguments to the program. This skips over the first argument.
Detail When the "folder" flag is detected, we set the folder_next variable to true.
Finally 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(); // Loop over arguments. for argument in env::args() { // Display arguments. println!("Argument: {}", argument); // Use flag after "-folder" was detected to set argument. if folder_next { folder = argument; folder_next = false; continue; } // 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.
A 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 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 Dec 17, 2021 (new).
© 2007-2024 Sam Allen.