Home > Article > Backend Development > How Can I Read Keystrokes Directly into a Channel Without a Newline in Go?
Input Keystrokes Directly to Channel without Newline
In Go, standard input (stdin) is line-buffered by default. This implies that keystrokes are not immediately sent to a channel; instead, they are held until a newline character is inputted. To overcome this limitation, here's how you can read keystrokes and send them to a channel without the need for a newline:
<code class="go">func chars() <-chan byte { ch := make(chan byte) reader := bufio.NewReader(os.Stdin) go func() { for { char, err := reader.ReadByte() if err != nil { log.Fatal(err) } ch <- char } }() return ch }</code>
However, stdin line buffering is not specific to Go but rather a platform-wide default. For non-buffered input, platform-specific solutions are required. One option is to use the ncurses or go-termbox packages. Alternatively, you can implement manual input handling with termios or Go syscalls (for Linux). Windows implementation requires exploration of ncurses or termbox source code.
The above is the detailed content of How Can I Read Keystrokes Directly into a Channel Without a Newline in Go?. For more information, please follow other related articles on the PHP Chinese website!