How to Get Input From User in Golang

1. Introduction

Getting input from a user is a common task in many programs. In Go, this can be achieved in various ways, depending on the nature of the input required. This post will explore two common methods: using the fmt.Scan family of functions and bufio.NewReader.

Definition

- fmt.Scanln & fmt.Scanf: These functions from the fmt package are used for simple, space-delimited input.

- bufio.NewReader: Part of the bufio package, this is used for reading more complex input such as whole lines, including spaces.

2. Program Steps

1. Use fmt.Scanln to read space-delimited input.

2. Use bufio.NewReader and ReadString for multiline or space-inclusive input.

3. Print the captured input to confirm the operation.

3. Code Program

package main

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

func main() {
	// Using fmt.Scanln
	fmt.Println("Enter your favorite color:")
	var color string
	fmt.Scanln(&color)

	// Using bufio.NewReader
	fmt.Println("Enter a brief bio:")
	reader := bufio.NewReader(os.Stdin)
	bio, _ := reader.ReadString('\n') // Ignoring error for brevity

	// Output the results
	fmt.Printf("Favorite Color: %s\n", color)
	fmt.Printf("Bio: %s\n", strings.TrimSpace(bio)) // Trimming newline character
}

Output:

Enter your favorite color:
Blue
Enter a brief bio:
I enjoy long walks on the beach and coding in Go.
Favorite Color: Blue
Bio: I enjoy long walks on the beach and coding in Go.

Explanation:

1. The program starts with package main indicating it's an executable program.

2. import statements include necessary packages: fmt for input/output, bufio for buffered I/O, os for accessing the operating system features, and strings for string manipulation.

3. fmt.Println prompts the user to enter their favorite color.

4. var color string declares a variable to store the color.

5. fmt.Scanln(&color) reads the next word from standard input and assigns it to color.

6. fmt.Println then prompts for a brief bio.

7. bufio.NewReader(os.Stdin) creates a new reader that buffers input from standard input.

8. reader.ReadString('\n') reads the input from the user until a newline is encountered.

9. The bio is printed using fmt.Printf with strings.TrimSpace to remove the newline character from the ReadString method.

10. The output shows the color and bio as entered by the user, indicating the input was successfully captured.


Comments