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:
"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:
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:
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:
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:
…
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:
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.