Skip to Content
Course content

214: Building Interactive Prompts

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.