How it works...

In order to read from the standard console input, stdin, we first need to obtain a handle to it. We do this by calling io::stdin() [29]. Imagine the returned object as a reference to a global stdin object. This global buffer is managed by a Mutex, which means that only one thread can access it at a time (more on that later in the book, in the Parallelly accessing resources with Mutexes section in Chapter 7, Parallelism and Rayon). We get this access by locking (using lock()) the buffer, which returns a new handle [31]. After we have done this, we can call the lines method on it, which returns an iterator over the lines the user will write [31 and 52]. More on iterators in the Accessing collections as Iterators section in Chapter 2, Working with Collections.

Finally, we can iterate over as many submitted lines as we want until some kind of break condition is reached, otherwise the iteration would go on forever. In our example, we break the number-checking loop as soon as a valid number has been entered [56].

If we're not particularly picky about our input and just want the next line, we have two options:

  • We can continue using the infinite iterator provided by lines(), but simply call next on it in order to just take the first one. This comes with an additional error check as, generally speaking, we cannot guarantee that there is a next element.

  • We can use read_line in order to populate an existing buffer [43]. This doesn't require that we lock the handler first, as it is done implicitly.

Although they both result in the same end effect, you should choose the first option. It is more idiomatic as it uses iterators instead of a mutable state, which makes it more maintainable and readable.

On a side note, we are using print! instead of println! in some places in this recipe for aesthetic reasons [22]. If you prefer the look of newlines before user input, you can refrain from using them.

..................Content has been hidden....................

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