GoLang Series Part 4: User Input from Keyboard

GoLang Series Part 4: User Input from Keyboard

ยท

2 min read

Introduction

In this part of the Go series, we will learn how to handle user input from the keyboard. Handling user input is a fundamental aspect of creating interactive applications. Go provides straightforward ways to read input from the standard input (keyboard) using packages like bufio and os.

Example

Let's look at an example where we will prompt the user to enter their name, and then we will greet them. Additionally, we will demonstrate how to handle potential errors when opening a file.

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    initMessage := "This is an example for UserInput from Keyboard"
    fmt.Println(initMessage)

    reader := bufio.NewReader(os.Stdin)
    fmt.Println("What is Your Name?")

    input, _ := reader.ReadString('\n')
    fmt.Println("Hi,", input)
    fmt.Printf("The entered value is of Type: %T\n", input)

    file, err := os.Open("newfile.txt")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("The file exists:", file)
}

How to Run

  1. Save the code in a file named main.go.

  2. Open your terminal or command prompt.

  3. Navigate to the directory where main.go is saved.

  4. Run the command: go run main.go.

  5. Follow the prompt to enter your name.

Output

When you run the program, you will see the following output:

This is an example for UserInput from Keyboard
What is Your Name?
<your_name>
Hi, <your_name>
The entered value is of Type: string

If the file newfile.txt exists in the same directory, it will print:

The file exists: &{0xc000010260}

If the file does not exist, it will print an error message and terminate the program.

Explanation

  • Initialization: We print an initial message to the console.

  • Buffered Reader: We create a bufio.Reader to read input from the standard input (os.Stdin).

  • Reading Input: We prompt the user for their name and read the input using reader.ReadString('\n'). This function reads until the newline character is encountered.

  • Greeting the User: We print a greeting message including the user's input.

  • Type Printing: We print the type of the user input, which is a string.

  • File Handling: We attempt to open a file named newfile.txt. If the file does not exist, os.Open returns an error which is handled by log.Fatal. This function logs the error and stops the execution of the program.

Conclusion

In this part, we covered how to read user input from the keyboard in Go and handle basic file operations. These skills are essential for developing interactive applications. In the next part, we will dive into the "comma ok" or "error ok" syntax in Go, which is a common pattern for error handling and type assertions.

Next: Comma OK or Error OK Syntax in Go

Did you find this article valuable?

Support NavyaDevops by becoming a sponsor. Any amount is appreciated!

ย