In this article, we will be discussing and writing practical code on how to take or parse multiple inputs from users in Golang.
Different methods to parse multiple inputs from user
Golang is a procedural language, Reading a user's inputs requires variables assigning, processing it into the standard output such as a monitor. Golang provides standard libraries such as fmt
and bufio
packages, help us with various function in reading and displaying users inputs. In a nutshell, reading inputs involves:-
- using a standard package that has input and output functions.
- Declare a variable that holds the inputs to be displayed.i.e
var variableName datatype
- Using a standard library like
fmt.Scan()
to read and store input into variable defined.
The following are functions used to read users' inputs in Golang:-
fmt.Scanln()
fmt.Scanf()
bufio.NewReader()
Method 1:- fmt.Scanln()
Golang fmt
package does not only provide us with the capability to format data into various forms and print the output on the terminal, Its robust in the way to lets users enter multiple values stored into a various variables to hold respective inputs of different types using fmt.Scanln()
. It's one of the examples of vardiac functions used in golang. It accepts an ellipses of data interface, i.e func Scanln( val ...anyType)(return integerValue, error)
. It returns a response of integer and error types. All inputs are captured in a single sentence. The integer value represents the total number of inputs provided For example Reading user information into a struct.
package main
import (
"fmt"
)
type Person struct {
FullName string
TelephoneNo int64
Occupation string
Country_Of_Residence string
}
func main() {
fmt.Println("Kindly enter your data in following order: ")
var firstname, lastname, occupation, country string
var phoneNo int64
fmt.Println(" firstname, lastname, occupation, country, phoneNo")
totalInputs, errReading := fmt.Scanln(&firstname, &lastname, &country, &occupation, &phoneNo)
if errReading != nil {
fmt.Printf("Your input could not be read%v", errReading)
}
//fullname
fullname := fmt.Sprintf("%v %v", firstname, lastname)
// map values into struct
person := Person{
fullname,
phoneNo,
occupation,
country,
}
fmt.Printf(" you entered a total of %v items into scanln function", totalInputs)
fmt.Println("\n----------Your Data is as follows .........")
fmt.Println("\nFullName\tPhoneNo\tOccupation\tCountry of Residence ")
fmt.Println(person)
}
Output:
$ go run main.go
Kindly enter your data in the following order:
firstname, lastname, occupation, country, phoneNo
John Doe USA DataScientist 01233333
you entered a total of 5 items into scanln function
----------Your Data is as follows .........
FullName PhoneNo Occupation Country of Residence
{John Doe 341723 DataScientist USA}
Explanation:- In the above code, we declare variables to hold various input values. Reading is made by fmt.Scanln()
function, which gets a pointer to the variable defined. It returns the total number of inputs made by the user. we can map the values into a struct and print out the results.
Method 2:- fmt.Scanf()
fmt.Scanf()
is a function provided by the fmt
package in Golang standard libraries. It reads users' inputs values in the standard input (stdin) and this values format i.e "%v, %s,%2f"
is determined then stored in a variable. For example of multiple inputs:-
package main
import (
"fmt"
)
func areaTriangle(base, height float64) float64 {
return 0.5 * base * height
}
func main() {
var base, height float64
fmt.Println("Kindly enter the base and height values, separated by space to determine the area of a triangle")
_, err := fmt.Scanf("%2f %2f", &base, &height)
if err != nil {
fmt.Printf("Sorry an error occurred %v", err)
}
result := areaTriangle(base, height)
fmt.Printf("The area of the triangle is %v", result)
}
Output:
$ go run main.go
Kindly enter the base and height values, separated by space to determine the area of a triangle
3 4
The area of the triangle is 6
Explanation: In above code, we are reading data of type float64 and using "%2f
" convert it to a specific float format, then the variable values are passed to areaTriangle()
function to calculate the area , results displayed on the terminal.
Method 3:- bufio.NewReader()
Using golang standard library one can create a command line interface known as CLI. This tool is just an emulation of Terminal in macOS and Linux or PowerShell in windows operating systems. Here users can type a whole sentence or short sentences. Golang provides us with bufio.NewReader()
which can read and store users' input into a variable. It Golang function that returns multiple values. For example :
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
fmt.Println("Kindly Provide a brief Description of GolinuxCloud company: once done typing, kindly tap enter button to display your content.")
// using standard input in this case its the terminal
// once done
userData, err := bufio.NewReader(os.Stdin).ReadString('\n');
if err != nil {
_ = fmt.Errorf(" %v error", err)
return
}
// Display user's data stdout
results:= strings.TrimSuffix(userData, "\n")
fmt.Printf("Results you Provided: \n %v", results)
}
Output:-
$ go run main.go
Kindly Provide a brief Description of the GolinuxCloud company:
It's an online academic platform, It's enriched with numerous technology materials. DevOps, Web, IOS, and Android developer visit here for upskilling....
Results you Provided:
It's an online academic platform, It's enriched with numerous technology materials. DevOps, Web, IOS, and Android developer visit here for upskilling....
Explanation:- In the above code, we are making use of bufio.NewReader()
function, from bufio
package in golang standard library. It takes parameters implemented by io.Reader
packages such as os.Stdin
or StdEr
etc. os.StdIn
works as an interface and opens the file that points to standard inputs i.e command line interface or terminal. The last event of delimeter()
known as '\n' refers to enter key which inserts a new line using the ReadString()
function and returns data containing the delimiter. Here the sentence ends with the '\n
' character and we have to remove it using string.TrimSuffix()
method allows us to pass the data followed by the special character to remove. upon tapping enter key. we use the fmt.Printf()
function to display the user's results content on the terminal.
Summary
In a nutshell, in this article, we have discussed a few ways we can read users' inputs from the standard input and display using standard output i.e terminal. Using golang you can develop different tools to interact with the command line interface. You can read more about cobra
framework for developing CLI applications in golang. Flags and OS packages too can help you design a well-programmed CLI of your choice.
References