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.
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.
for
-loop to iterate over the arguments to the program. This skips over the first argument.folder_next
variable to true.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, notesIf 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.
String::new
for the folder variable.String
objects instead of str
references is often a good solution to borrowing problems.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.