Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rust

How to accept command line arguments in Rust

Mohe Ud Din Sheikh

Overview

A command line argument is a collection of values or specifiers supplied to the terminal. Therefore, these parameters can change the program’s behavior, as described in the source code. Let's look at Rust's syntax.

Syntax

    let args: Vec<String> = env::args().collect();
Accept command line arguments in Rust
  • env::args().collect();: This returns the argument passed in the terminal.

Pass an argument in the terminal

We use cargo run to pass an argument through the terminal:

cargo run a b c
Pass an argument in the terminal

Example

use std::env;
  
fn main() {
    let args: Vec<String> = env::args().collect();
    println!("We got {:?} arguments: {:?}.", args.len()-1, &args[1..]);
}

Explanation

  • Line 1: We use the Rust library, std::env;. It returns an iterator of the command line arguments supplied.
  • Lines 4 and 5: We use env::args().collect();. This returns the argument passed in the terminal and shows the number of arguments.

RELATED TAGS

rust

CONTRIBUTOR

Mohe Ud Din Sheikh
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring