golang

Golang Read From STDIN

In most programming languages, you have the ability to read input from the console and store it into a variable. Go programming is not left behind in that regard. In this article, we will learn how you can read input from the console in Go programming.

Required Imports

To read input from the console, we need to import a few packages. The first is the bufio package, fmt package, and the os package.

The bufio package allows you to read characters from the STDIN at once. The fmt package is used to handle I/O operations, and the os provides low-level system functionalities.

The following snippet imports all the required packages:

import (
    "bufio"
    "fmt"
    "os"
)

Golang Read Character

Let us see how you can read a single Unicode character from the stdin in the Go language. Consider the following code provided:

package main
import (
    "bufio"
    "fmt"
    "log"
    "os"
)
func main() {
    fmt.Println("Type a character > ")
    reader := bufio.NewReader(os.Stdin)
    char, _, err := reader.ReadRune()

    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Unicode char: %U\n", char)
}

In the previous example, we create a new reader from the bufio package and pass the os.Stdin as the parameter.

We then read the character and the error from the reader. Notice we use the ReadRune() method to return a Unicode character.

The previous code should return an output as shown:

Type a character >
A
Unicode char: U+0041

The output above shows the Unicode code point for the character “A.”

Golang Read Multi-Line

If you want to read multiple lines from the console, you can use the ReadString() method instead of ReadRune, as shown above.

A code example is provided below:

package main
import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    fmt.Println("Enter a string")
    reader := bufio.NewReader(os.Stdin)
    str, err := reader.ReadString('\n')
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s", str)
}

In this example, the reader will continuously read the input from the user until it encounters the specified delimiter. In our example, if the reader encounters a new-line character, it stops reading.

If we run the code, we should get an output as:

Enter a string

hello world from stdin

Golang Scanner

Another method we can use to accept input from stdin is the scanner method. The NewScanner() method is very useful when reading a file. However, we can use it to read from stdin.

A code example is shown below:

package main
import (
    "bufio"
    "fmt"
    "os"
)
func main() {
    scanner := bufio.NewScanner((os.Stdin))
    input := make([]string, 0)
    for {
        fmt.Println("Type here: ")
        scanner.Scan()
        txt := scanner.Text()
        input = append(input, txt)
        break
    }
    fmt.Println(input)
}

The previous code reads the input from the user and appends it to the input slice. You can expand the previous code to continuously read the input and terminate once no value is provided.

Conclusion

As seen from this guide, Go programming provides us with several ways to read input from the STDIN. You can pick any method that suits your needs. We hope you found this article helpful. Check out other Linux Hint Articles for more tips and tutorials.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list