Non-Blocking Character Input in Go
Reading a character from standard input without pressing Enter can be achieved using Go's standard library and executing operating system commands.
For Windows users, a non-canonical input mode may be available using the syscall package. However, this approach is platform-dependent and may not be suitable cross-platform development.
UNIX-Based Solution
The provided solution works for UNIX-based systems and disables input buffering and character echoing:
package main import ( "fmt" "os" "os/exec" ) func main() { // disable input buffering exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run() // do not display entered characters on the screen exec.Command("stty", "-F", "/dev/tty", "-echo").Run() var b []byte = make([]byte, 1) for { os.Stdin.Read(b) fmt.Println("I got the byte", b, "("+string(b)+")") } }
This program will repeatedly read a character from standard input until it is terminated. The cbreak mode disables line buffering, while the -echo flag prevents the entered character from being displayed on the screen.
Note:
This solution assumes that you are using a terminal emulator that supports non-canonical input mode. If your terminal does not support it, you may need to adjust the code accordingly.
The above is the detailed content of How Can I Achieve Non-Blocking Character Input in Go?. For more information, please follow other related articles on the PHP Chinese website!