User Input and Output
# 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, thefmt package handles all basic Input/Output (I/O).
2. Learning Objectives
By the end of this chapter, you will be able to:-
Use
fmt.Printandfmt.Printlneffectively.
-
Master formatted output using
fmt.Printf(String Interpolation).
-
Read user input using
fmt.Scanandfmt.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.
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).
5. fmt.Scan vs fmt.Scanln
-
fmt.Scanreads text separated by spaces. If you type "Alice Smith", it will only store "Alice" in the first variable, and save "Smith" for the nextScancall.
-
fmt.Scanlnis 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!7. Common Mistakes
-
Forgetting the Ampersand (
&): Writingfmt.Scan(firstName)instead offmt.Scan(&firstName). The code will compile, but the variable won't update because Go didn't know the memory address.
-
Using
Printfwithout\n:fmt.Printfdoes NOT automatically add a new line at the end likePrintln. If you forget the\n, your next print statement will jam onto the same line.
8. Best Practices
-
Use
%vfor debugging: If you aren't sure what type a variable is,%vis incredibly useful as it dynamically adapts to print almost anything.
-
Use
%Tfor 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.
Write a program that asks the user for the radius of a circle as a
float64.
-
2.
Calculate the area (
3.14159 * radius * radius).
-
3.
Print the area strictly formatted to 2 decimal places using
fmt.Printf.
10. MCQs with Answers & Explanations
Which function is used for formatted string output in Go?
What does the formatting verb %v do?
Which verb prints the exact Data Type of a variable?
How do you print a float restricted to two decimal places?
Which function waits for user input from the terminal?
What symbol MUST precede the variable name inside fmt.Scan?
What happens if you forget the \n inside a fmt.Printf string?
What happens if you use fmt.Scan(&name) and the user types "John Doe"?
Which verb is specifically used to format integers (base 10)?
What does the fmt package name stand for?
11. Interview Preparation
Interview Questions:-
1.
Why must we use pointers (
&) when reading input withfmt.Scan?
-
2.
Explain the difference between
%v,%s, and%Tinfmt.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
Thefmt 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 useif, else, and switch statements to control the flow of our application.