Book Image

Rust Standard Library Cookbook

By : Jan Hohenheim, Daniel Durante
Book Image

Rust Standard Library Cookbook

By: Jan Hohenheim, Daniel Durante

Overview of this book

Mozilla’s Rust is gaining much attention with amazing features and a powerful library. This book will take you through varied recipes to teach you how to leverage the Standard library to implement efficient solutions. The book begins with a brief look at the basic modules of the Standard library and collections. From here, the recipes will cover packages that support file/directory handling and interaction through parsing. You will learn about packages related to advanced data structures, error handling, and networking. You will also learn to work with futures and experimental nightly features. The book also covers the most relevant external crates in Rust. By the end of the book, you will be proficient at using the Rust Standard library.
Table of Contents (12 chapters)

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 }