Home > Backend Development > Golang > How Can I Read Single Characters from Standard Input Instantly in Go?

How Can I Read Single Characters from Standard Input Instantly in Go?

Patricia Arquette
Release: 2024-12-13 14:17:14
Original
804 people have browsed it

How Can I Read Single Characters from Standard Input Instantly in Go?

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)+")")
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template