Go User Input

Introduction

Reading user input in Go can be done using various methods depending on the source of the input, such as from the command line, files, or other input streams. In this chapter, you will learn how to read user input from the command line using the fmt package and the bufio package.

Reading Input with fmt.Scan

The fmt package provides simple functions to read formatted input from standard input.

Example: Reading a Single Value

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 example, fmt.Scan reads a single value from the user and stores it in the name variable.

Example: Reading Multiple Values

Example:

package main

import "fmt"

func main() {
    var name string
    var age int
    fmt.Print("Enter your name and age: ")
    fmt.Scan(&name, &age)
    fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
}

In this example, fmt.Scan reads two values from the user and stores them in the name and age variables.

Reading Input with fmt.Scanf

The fmt.Scanf function allows you to specify a format for the input.

Example: Using fmt.Scanf

Example:

package main

import "fmt"

func main() {
    var name string
    var age int
    fmt.Print("Enter your name and age: ")
    fmt.Scanf("%s %d", &name, &age)
    fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
}

In this example, fmt.Scanf reads input based on the specified format string.

Reading Input with bufio

For more complex input handling, you can use the bufio package, which provides buffered input and output.

Example: Reading a Line of Input

Example:

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter your name: ")
    name, _ := reader.ReadString('\n')
    fmt.Printf("Hello, %s", name)
}

In this example, bufio.NewReader is used to create a new reader, and ReadString reads a line of input until the newline character.

Example: Reading Input and Handling Errors

Example:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter your name: ")
    name, err := reader.ReadString('\n')
    if err != nil {
        fmt.Println("An error occurred:", err)
        return
    }
    name = strings.TrimSpace(name)
    fmt.Printf("Hello, %s!\n", name)
}

In this example, error handling is added to ensure the program responds appropriately if an error occurs during input reading.

Example: Reading Multiple Lines

Example:

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Println("Enter text (type 'STOP' to end):")

    for {
        text, _ := reader.ReadString('\n')
        if text == "STOP\n" {
            break
        }
        fmt.Printf("You typed: %s", text)
    }
}

In this example, a loop is used to read multiple lines of input until the user types "STOP".

Conclusion

Reading user input in Go can be achieved using the fmt and bufio packages. The fmt package is suitable for simple input scenarios, while the bufio package provides more flexibility and control for complex input handling. By understanding how to use these packages, you can effectively read and process user input in your Go programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top