User input in Golang with example #3
A Beginner's Guide to Getting User Input in Go
Play this article
In Go, you can use the fmt
package to get user input from the command line. Here is an example of how to get user input in Go:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// Print a prompt to the user
fmt.Print("Enter your name: ")
// Create a new reader to read from the standard input
reader := bufio.NewReader(os.Stdin)
// Read a single line of input
input, _ := reader.ReadString('\n')
// Print the input back to the user
fmt.Println("Hello, ", input)
}
When this program is run, it will print a prompt to the user asking for their name. The user can then enter their name and press the enter key. The program will then print a greeting to the user using their input.
You can also use the fmt.Scanf
function to get user input and parse it into a specific type. For example, to get a number from the user, you can do the following:
package main
import "fmt"
func main() {
// Print a prompt to the user
fmt.Print("Enter a number: ")
// Declare a variable to store the user input
var num int
// Read a single number from the standard input and store it in the num variable
fmt.Scanf("%d", &num)
// Print the number back to the user
fmt.Println("You entered: ", num)
}
In this example, the program will print a prompt asking the user to enter a number. The user can then enter a number and press the enter key. The program will then print the number back to the user.