How to do it...

  1. In the bin folder, create a file called cli_params.rs

  2. Add the following code and run it with cargo run --bin cli_params some_option some_other_option:

1   use std::env;
2
3 fn main() {
4 // env::args returns an iterator over the parameters
5 println!("Got following parameters: ");
6 for arg in env::args() {
7 println!("- {}", arg);
8 }
9
10 // We can access specific parameters using the iterator API
11 let mut args = env::args();
12 if let Some(arg) = args.nth(0) {
13 println!("The path to this program is: {}", arg);
14 }
15 if let Some(arg) = args.nth(1) {
16 println!("The first parameter is: {}", arg);
17 }
18 if let Some(arg) = args.nth(2) {
19 println!("The second parameter is: {}", arg);
20 }
21
22 // Or as a vector
23 let args: Vec<_> = env::args().collect();
24 println!("The path to this program is: {}", args[0]);
25 if args.len() > 1 {
26 println!("The first parameter is: {}", args[1]);
27 }
28 if args.len() > 2 {
29 println!("The second parameter is: {}", args[2]);
30 }
31 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.42.134