Skip to main content
Go Language Fundamentals for Beginners to Advanced
CHAPTER 06 Beginner

User Input and Output

Updated: May 17, 2026
5 min read

# CHAPTER 6

User Input and Output

1. Introduction

A backend system is useless if it cannot accept incoming data and return formatted responses. While modern backends communicate via JSON over the internet, we must first learn how to read raw text from the terminal and format strings perfectly. In Go, the fmt package handles all basic Input/Output (I/O).

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use fmt.Print and fmt.Println effectively.
  • Master formatted output using fmt.Printf (String Interpolation).
  • Read user input using fmt.Scan and fmt.Scanln.
  • Understand memory addresses when scanning data.

3. Formatting Output (fmt.Printf)

We already know fmt.Println prints text and adds a new line. But what if we want to build a complex string mixing text and variables?

Instead of ugly concatenation like fmt.Println("User " + name + " is " + age + " years old"), Go uses fmt.Printf (Print Format).

It uses "Verbs" (placeholders starting with %) that are replaced by variables.

go
1234567891011121314
package main
import "fmt"

func main() {
    name := "Alice"
    age := 28
    score := 95.5

    // %s is for strings, %d is for base-10 integers, %f is for floats
    fmt.Printf("User: %s | Age: %d | Score: %f\n", name, age, score)
    
    // Formatting a float to only show 2 decimal places: %.2f
    fmt.Printf("Formatted Score: %.2f\n", score)
}

Common Formatting Verbs:

  • %v (Value): Prints the value in its default format (A great catch-all!).
  • %T (Type): Prints the data type of the variable (e.g., int, string).
  • %s: String.
  • %d: Integer.
  • %f: Float.

4. Reading User Input (fmt.Scan)

To ask the user for data, we use fmt.Scan. This function stops the program and waits for the user to type something and press Enter.

Memory Concept: When you use Scan, you must tell Go exactly *where in memory* to put the typed data. You do this by placing an ampersand (&) before the variable name. This is called a Pointer. (We will dive deep into pointers in Chapter 13).

go
123456789101112131415
package main
import "fmt"

func main() {
    var firstName string
    var age int

    fmt.Print("Enter your first name: ")
    fmt.Scan(&firstName) // The & tells Go where to store the typed text

    fmt.Print("Enter your age: ")
    fmt.Scan(&age)

    fmt.Printf("\nWelcome %s! You are %d years old.\n", firstName, age)
}

5. fmt.Scan vs fmt.Scanln

  • fmt.Scan reads text separated by spaces. If you type "Alice Smith", it will only store "Alice" in the first variable, and save "Smith" for the next Scan call.
  • fmt.Scanln is similar, but it explicitly stops reading the moment the user presses the Enter key.

6. Mini Project: User Profile CLI

Let's build an interactive terminal app!
go
12345678910111213141516171819
package main
import "fmt"

func main() {
    var user string
    var balance float64

    fmt.Println("--- BANK REGISTRATION ---")
    
    fmt.Print("Enter Username: ")
    fmt.Scanln(&user)
    
    fmt.Print("Enter Initial Deposit ($): ")
    fmt.Scanln(&balance)
    
    fmt.Println("-------------------------")
    // Use %v as an easy placeholder, and %.2f for currency
    fmt.Printf("Success! Account '%v' created with a balance of $%.2f\n", user, balance)
}

7. Common Mistakes

  • Forgetting the Ampersand (&): Writing fmt.Scan(firstName) instead of fmt.Scan(&firstName). The code will compile, but the variable won't update because Go didn't know the memory address.
  • Using Printf without \n: fmt.Printf does NOT automatically add a new line at the end like Println. If you forget the \n, your next print statement will jam onto the same line.

8. Best Practices

  • Use %v for debugging: If you aren't sure what type a variable is, %v is incredibly useful as it dynamically adapts to print almost anything.
  • Use %T for type checking: If Go inferred a type using := and you are confused, fmt.Printf("Type is %T", myVar) will tell you exactly what it is.

9. Exercises

  1. 1. Write a program that asks the user for the radius of a circle as a float64.
  1. 2. Calculate the area (3.14159 * radius * radius).
  1. 3. Print the area strictly formatted to 2 decimal places using fmt.Printf.

10. MCQs with Answers & Explanations

Question 1

Which function is used for formatted string output in Go?

Question 2

What does the formatting verb %v do?

Question 3

Which verb prints the exact Data Type of a variable?

Question 4

How do you print a float restricted to two decimal places?

Question 5

Which function waits for user input from the terminal?

Question 6

What symbol MUST precede the variable name inside fmt.Scan?

Question 7

What happens if you forget the \n inside a fmt.Printf string?

Question 8

What happens if you use fmt.Scan(&name) and the user types "John Doe"?

Question 9

Which verb is specifically used to format integers (base 10)?

Question 10

What does the fmt package name stand for?

11. Interview Preparation

Interview Questions:
  1. 1. Why must we use pointers (&) when reading input with fmt.Scan?
  1. 2. Explain the difference between %v, %s, and %T in fmt.Printf.

Debugging Task: A junior developer writes fmt.Printf("User is %d years old", "Twenty") and it prints garbled formatting errors. Why? *Answer: %d requires an integer, but a string was provided. Use %s for strings.*

12. Summary

The fmt package provides complete control over terminal I/O. fmt.Printf is a powerful tool for injecting variables into text, while fmt.Scan allows us to read user input. Recognizing the need for the memory address operator (&) is your first step toward mastering Go's underlying memory management.

13. Next Chapter Recommendation

Now that our programs are interactive, they need the ability to make decisions based on user input. In Chapter 7: Conditional Statements, we will learn how to use if, else, and switch statements to control the flow of our application.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·