官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 唐海县| 公主岭市| 京山县| 卢湾区| 长岛县| 哈巴河县| 兴和县| 屏东县| 古蔺县| 永泰县| 石河子市| 木兰县| 北宁市| 石门县| 香河县| 伊宁市| 潜江市| 工布江达县| 余庆县| 日照市| 格尔木市| 九龙坡区| 贵港市| 托克托县| 平顶山市| 航空| 云和县| 新龙县| 宁南县| 股票| 龙井市| 清流县| 嘉善县| 永城市| 盐边县| 巫山县| 兴义市| 镇江市| 彰武县| 榆社县| 卢湾区|