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 package import( "fmt" ) //program execution starts here func main(){ //Display what you want from user fmt.Println("Enter your age: ") //Declare variable to store input var age int //Take input from user fmt.Scanln(&age) //Display age with statement fmt.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.RELATED TAGS
CONTRIBUTOR
View all Courses