How to read input in go lang!
- Maheshwar
- go, Uncategorized
- Jan 31, 2021
In this article, we demonstrate how to read input from console in go language. Till now we saw how to display output on the screen using fmt.println(). Standard input sometimes abbreviated as stdin basically it’s a stream to read the user input. To display output we used the fmt package the same way to read input we use the fmt
, bufio
, and os
packages.
Scanf to read input:
The fmt.Scanf() function in Go language scans the input texts which is given in the standard input, reads from there, and stores the successive space-separated values into successive arguments as determined by the format.
Syntax:
func Scanf(format string, a ...interface{}) (n int, err error)
Input Param
- format string: These are the different formats that are used for each given element.
- a …interface{}: These parameters receive each given elements.
Returns: It returns the number of items successfully scanned.
package main
import "fmt"
func main() {
var name string
fmt.Print("Enter your good name: ")
fmt.Scanf("%s", &name)
fmt.Println("Hello ", name)
}
Output:
$ go run readinput.go
Enter your good name: Maheshwar
Hello Maheshwar
In this example, on console prompts the end user to enter his name.
var name string
Using Scanf function to read input
fmt.Scanf("%s", &name)
This function read the input from standard input and assign that value to variable name.
Let us check the code snippet to read more than one value.
func read2value(){
var name string
var age int
fmt.Print("Enter your name & age: ")
fmt.Scanf("%s %d", &name, &age)
fmt.Printf("%s is %d years old\n", name, age)
}
Output:
$ go run readinput.go
Enter your name & age: Maheshwar 28
Maheshwar is 28 years old
In the above code snippet, the scanf function reads two inputs name and age.
Read input with NewScanner:
The go lang is shipped with the bufio i.e the buffered I/O. It helps to process a stream of data by splitting it into tokens and removing space between them. The Scanner
provides a convenient interface for reading data such as a file of newline-delimited lines of text.
package main
import (
"fmt"
"bufio"
"os"
)
func main(){
names := make([]string, 0)
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Enter Patient name: ")
scanner.Scan()
text := scanner.Text()
if len(text) != 0 {
fmt.Println(text)
names = append(names, text)
} else {
break
}
}
fmt.Println(names)
}
The above program is executing unless and until the user presses enter button. It is accepting the patient’s name any number of times. This program ends when the input string length is zero.
if len(text) != 0 {
fmt.Println(text)
names = append(names, text)
} else {
break
}
scanner := bufio.NewScanner(os.Stdin)
A new scanner is created from standard input.
names := make([]string, 0)
Created empty slices that holds the list of patient names.
Output:
$ go run bufioscane.go
Enter Patient name: Ram
Ram
Enter Patient name: Sham
Sham
Enter Patient name: Govind
Govind
Enter Patient name: Rocky
Rocky
Enter Patient name: David
David
Enter Patient name:
Patient names::
[Ram Sham Govind Rocky David]
Read input with NewReader in go:
Go language support I/O classes similar to java and C language like standard buffer IO reader-writer stream reader writer. Buffered IO reader-writer has much better performance than non-buffered reader writer.

package main
import (
"fmt"
"bufio"
"os"
)
func main(){
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your friend name: ")
name, _ := reader.ReadString('\n')
fmt.Printf("Hello %s\n", name)
}
reader := bufio.NewReader(os.Stdin)
create newReader from standard input to read the input from end user.
Output:
$ go run readerbuf.go
Enter your friend name: Vicky
Hello Vicky
name, _ := reader.ReadString(‘\n’)
This ReadString() function reads the input until it encounters the delimiter in this case its new-line (\n). There are other data specific method toread the input.
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error)
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error)
func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error)
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error)
Conclusion:
In this article, we learned to read input from standard input and assign that to variables. Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.
You must log in to post a comment.