In this shot, we will learn how to take user input in Golang.
Golang has a function called Scanln
that is provided by the fmt
package and used to take input from the user.
fmt.Scan(&variablename)
fmt.Scanln(&variablename)
Where:
fmt
is the package nameScan
or Scanln
is the function that takes input&variablename
is the reference to the variable where we need to store the user inputIn the example below, we take the user’s age as input and display a simple statement. We can perform any operation on the user input, such as sending it to the server when the user submits their form.
package main//import fmt packageimport("fmt")//program execution starts herefunc main(){//Display what you want from userfmt.Println("Enter your age: ")//Declare variable to store inputvar age int//Take input from userfmt.Scanln(&age)//Display age with statementfmt.Println("You are ",age," years old.")}
Enter the input below
fmt
package.main()
function.age
of type int
to store the input.Scanln
function and pass the age
variable as the parameter. When the user enters input, it will be stored in the age
variable.