Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
214: Building Interactive Prompts
I want to build a small CLI tool that helps me initialize a project manifest. Ideally, it should ask me for a project name and a brief description, then spit them back out in a formatted string. It sounds trivial, but if you've spent any time with Go, you know that getting input from a user is where things usually get weird.
The Scan Trap
My first instinct is always to reach for fmt.Scanln. It's right there in the standard library and it seems like the most direct path. Let's see what happens when I try to get a project name.
package main
import "fmt"
func main() {
var name string
fmt.Print("Enter project name: ")
fmt.Scanln(&name)
fmt.Printf("Project name set to: %s\n", name)
}
If I run this and type "MyProject", it works perfectly. But as soon as I try to be descriptive and type "Project Alpha", the program behaves strangely. It prints "Project name set to: Project" and then exits. I've lost "Alpha" entirely. This is because fmt.Scanln stops reading at the first whitespace it encounters. For a project name, that's a dealbreaker; most real-world names have spaces.
Switching to a Scanner
Since fmt.Scanln is too aggressive with whitespace, I need something that reads until it hits a newline character. That's where bufio comes in. I'll use a Scanner because it's generally cleaner for line-by-line input than using a Reader.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter project description: ")
scanner.Scan() // This waits for the user to hit Enter
description := scanner.Text()
fmt.Printf("Description: %s\n", description)
}
Now, "This is a great project" is captured in its entirety. This is much better. However, I'm noticing a pattern here: I have to call fmt.Print to ask the question, then scanner.Scan() to wait, then scanner.Text() to get the value. If I have five different prompts, my main function is going to be a wall of repetitive boilerplate.
Cleaning up the Noise
I also realized that if the user accidentally hits the spacebar before hitting enter, or if I'm reading from a file later, I might get trailing whitespace that I don't want. I need to sanitize this input. I'll wrap the logic into a helper function and use strings.TrimSpace to make it robust.
Here is how I'm thinking about it: the function should take the prompt string as an argument and return the cleaned-up response.
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func prompt(scanner *bufio.Scanner, label string) string {
fmt.Printf("%s: ", label)
scanner.Scan()
return strings.TrimSpace(scanner.Text())
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
name := prompt(scanner, "Project Name")
desc := prompt(scanner, "Project Description")
fmt.Printf("\n--- Manifest ---\nName: %s\nDesc: %s\n", name, desc)
}
Wait, why did I pass the scanner into the function instead of creating a new one inside? I've tried creating a new scanner inside the function before, and it causes a nightmare. If you create multiple scanners on os.Stdin, they start competing for the same input buffer. One scanner might "gobble up" the newline from a previous entry, leaving the next prompt to return an empty string instantly. Always create one scanner and pass it around.
Handling Empty Responses
One last thing. In a real tool, I can't let the user just hit Enter and leave the project name blank. I need a loop that persists until a valid answer is provided. I'll modify the prompt function to accept a "required" flag.
func promptRequired(scanner *bufio.Scanner, label string) string {
for {
fmt.Printf("%s (required): ", label)
scanner.Scan()
input := strings.TrimSpace(scanner.Text())
if input != "" {
return input
}
fmt.Println("Error: This field cannot be empty.")
}
}
Now we have a reliable way to interact with the user. We've moved from the fragile fmt.Scanln to a robust, reusable pattern using bufio.Scanner and strings.TrimSpace.
📋 Practical Task
Build a User Profile Creator
Create a CLI program that collects the following information from a user: Full Name, Favorite Programming Language, and Years of Experience.
- Implement a helper function to handle the prompting logic to avoid repetition.
- Ensure that Full Name is required (the program should loop until the user provides a non-empty string).
- Ensure that Favorite Programming Language allows spaces (e.g., "Visual Basic").
- At the end, print a summary of the profile in a clean, labeled format.
There are no comments for now.