Program arguments in Rust Programming


Taking care of arguments passed at the runtime is one of the key features of any programming language.

In Rust, we access these arguments with the help of std::env::args, which returns an iterator that gives us a string for each passed argument.

Example

Consider the example shown below −

use std::env;
fn main() {
   let args: Vec = env::args().collect();
   // The first argument is the path that was used to call the program.
   println!("My current directory path is {}.", args[0]);
   println!("I got {:?} arguments: {:?}.", args.len() - 1, &args[1..]);
}

We can pass arguments like this −

./args 1 2 3 4 5

Output:

My current directory path is ./args.
I got 5 arguments: ["1", "2", "3","4","5"].

Updated on: 03-Apr-2021

55 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements