RE: termion for loop

Using the termion crate, while it works perfectly, how come it infinitely takes input from my keyboard?

use termion::input::TermRead;
use termion::event::Key;
use std::process;

fn main()
    // Keys
    let keys = std::io::stdin().keys();
    for key in keys
        let key = key.expect("failed to read key");
        if key == Key::Char('q')

So here is the for loop, so does this for loop loops through infinite amount of times?

Just a few links:

  • std::io::stdin, which you use, returns Stdin.
  • Stdin implements Read, and therefore implements TermRead, via the blanket implementation. So, it provides the keys method, which returns Keys.
  • Implementation of Keys boils down to the implementation of Iterator for EventsAndRaw, which just reads the source two bytes at time.

And, finally, reading from Stdin ends when the corresponding handle is closed. If there's no redirection, i.e. standard input is connected to the terminal, that means - until the terminal itself is closed.

1 Like

If I understood you correctly, after executing let keys = std::io::stdin().keys();, Then in the next line which is for key in keys, it loops through infinitly because the list of keys is infinite?

There's not a "list of keys" anywhere in your code. There's iterator of keys, which wraps the standard input an ends when the input is closed.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.