function similar to getchar


Is there a Go function similar to C’s getchar able to handle tab press in console? I want to make some sort of completion in my console app.


C’s getchar() example:

#include <stdio.h>
void main()
    char ch;
    ch = getchar();
    printf("Input Char Is :%c",ch);

Go equivalent:

package main

import (

func main() {

    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('\n')

    fmt.Printf("Input Char Is : %v", string([]byte(input)[0]))

    // fmt.Printf("You entered: %v", []byte(input))

The last commented line just shows that when you press tab the first element is U+0009 (‘CHARACTER TABULATION’).

However for your needs (detecting tab) C’s getchar() is not suitable as it requires the user to hit enter. What you need is something like ncurses’ getch()/ readline/ jLine as mentioned by @miku. With these, you actually wait for a single keystroke.

So you have multiple options:

  1. Use ncurses / readline binding, for example or equivalent like

  2. Roll your own see for starting point

  3. use os.Exec to run stty or jLine.


Answered By – rputikar

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.