How it works...

Calling env::args() returns an iterator over the provided parameters[6]. By convention, the first command-line parameter on most operating systems is the path to the executable itself [12].

We can access specific parameters in two ways: keep them as an iterator [11] or collect them into a collection such as Vec[23]. Don't worry, we are going to talk about them in detail in Chapter 2, Working with Collections. For now, it's enough for you to know that:

  • Accessing an iterator forces you to check at compile time whether the element exists, for example, an if let binding [12]

  • Accessing a vector checks the validity at runtime

This means that we could have executed lines [26] and [29] without checking for their validity first in [25] and [28]. Try it yourself, add the &args[3]; line at the end of the program and run it.

We check the length anyways because it is considered good style to check whether the expected parameters were provided. With the iterator way of accessing parameters, you don't have to worry about forgetting to check, as it forces you to do it. On the other hand, by using a vector, you can check for the parameters once at the beginning of the program and not worry about them afterward.
..................Content has been hidden....................

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