Logo

Developer learning path

Go

User Input and Output in Go

User Input and Output

77

#description

In Go language, accepting user input and displaying output to the user is very easy. The standard library provides several packages that allow for user input and output. The two primary packages used for user input/output in Go are the fmt and bufio packages.

The fmt package is used for simple, formatted I/O like printing to standard output (or stdout) or reading input from standard input (or stdin). The fmt package is primarily used for printing to standard output.

For example, let's say we want to display a message to the user.

We can use the fmt package to achieve this:

                    
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}
                  

The above program will simply display the message "Hello, World!" to the user.

On the other hand, the bufio package provides buffered I/O, which allows you to read user input from the stdin. Buffered input means that it reads a line of text that is entered by the user, up to the newline character.

Here's an example:

                    
package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Print("Enter your name: ")
    scanner.Scan()
    name := scanner.Text()
    fmt.Println("Hello", name)
}
                  

The above program will accept input from the user in the form of a string and display it back with a greeting.

In summary, user input/output in Go is straightforward thanks to the built-in libraries. The fmt package handles simple I/O, while bufio provides buffered I/O for reading user input.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.