How to accept command line arguments in Rust
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.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved