Introduction

Interacting with users is a common requirement for many programs. In this guide, we'll explore how to handle user input in Go, including reading input from the command line, and demonstrate sample code to capture and process user-provided data.


Reading Input from the Command Line

You can read user input from the command line in Go using the fmt package and the Scan function. Here's an example:

                            package main
import "fmt"
func main() {
var name string
fmt.Print("Enter your name: ")
fmt.Scan(&name)
fmt.Printf("Hello, %s!\n", name)
}

In this code, the program prompts the user to enter their name, reads the input using fmt.Scan, and then greets the user with their name.


Parsing and Converting Input

User input is often received as strings, and you may need to parse and convert it to the desired data types. Here's an example of parsing and converting a string input into an integer:

                            package main
import (
"fmt"
"strconv"
)
func main() {
var ageStr string
fmt.Print("Enter your age: ")
fmt.Scan(&ageStr)
age, err := strconv.Atoi(ageStr)
if err != nil {
fmt.Println("Invalid input. Please enter a valid number.")
} else {
fmt.Printf("You are %d years old.\n", age)
}
}

In this code, we read the user's input as a string, convert it to an integer using strconv.Atoi, and handle potential conversion errors.


Input Validation

Validating user input is essential to ensure the data is correct and safe to use. You can use conditional statements to check for valid input. Here's an example of validating an email address:

                            package main
import (
"fmt"
"regexp"
)
func main() {
var email string
emailPattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
re := regexp.MustCompile(emailPattern)
fmt.Print("Enter your email address: ")
fmt.Scan(&email)
if re.MatchString(email) {
fmt.Printf("Email address '%s' is valid.\n", email)
} else {
fmt.Println("Invalid email address. Please enter a valid email.")
}
}

In this code, we use regular expressions to validate the email address provided by the user.


Further Resources

To continue learning about handling user input in Go, explore the following resources: