Read a single character, without pressing enter

I want to read a single character from stdin, and make it be available to the program even if \n is not at the end (ie: user types a character, character gets sent to program, no press of enter, basically like getch in curses)

I can currently only find the read_line function in std::io::Stdin, which does not do what i want as it waits for a newline and does not read a single character.

Is there a function that does this already? I've seen the read_char method from the console crate, but that also comes with a lot of extra stuff. I just want something that only reads chars, and nothing else!

The reason this requires a big complicated crate is that you have to switch the terminal to raw mode. Normally, the terminal does not give you access to the data at all until enter is pressed. This is necessary for backspace to work, since data cannot be taken back once its given to the program. Switching to raw mode requires you to handle stuff like backspace yourself instead.

8 Likes