Read Character from Standard Input Instantly in Go
In Go, reading from standard input typically requires pressing Enter to receive the input. However, if you want your application to respond immediately to any key press, similar to Console.ReadKey() in C#, the following solution can achieve that.
The provided code disables input buffering using stty commands, ensuring that keystrokes are processed instantly. Character echoing is also suppressed to prevent displayed input.
Here's the code:
package main import ( "fmt" "os" "os/exec" ) func main() { // Disable input buffering exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run() // Suppress input echoing 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)+")") } }
When this code is running, pressing any key immediately returns the character byte representation and corresponding character to the console.
The above is the detailed content of How Can I Read Single Characters from Standard Input Instantly in Go?. For more information, please follow other related articles on the PHP Chinese website!