ProgramGuru

The fmt Package

Start with The fmt Package

The fmt package formats values for humans and writes or reads text using verbs such as %s, %d and %v.

What you’ll learn

  • Explain the main purpose of the fmt package.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

fmt.Println writes arguments with appropriate spacing and a newline. fmt.Printf uses a format string; %d is an integer, %s a string, %.2f a floating-point value with two decimal places and %T a value’s type. fmt.Sprintf returns formatted text instead of printing it.

The Scan family reads input, but use fixed variables in this introductory example so it runs deterministically in online Go compilers.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for fmtFormatting and printing are separate operations.Values and verbsStep 1fmt.SprintfStep 2Formatted stringStep 3fmt.PrintlnStep 4Formatting and printing are separate operations.
Formatting and printing are separate operations.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	name, amount := "Mira", 12.5
	fmt.Printf("Customer: %s, total: %.2f\n", name, amount)
	label := fmt.Sprintf("Quantity: %d", 3)
	fmt.Println(label)
}

Output

Customer: Mira, total: 12.50
Quantity: 3

Trace what the program does

Printf substitutes the name and two-decimal amount. Sprintf creates a string without writing to output, and the final Println prints that string.

Avoid common mistakes

  • Printf does not automatically add a trailing newline unless the format contains one.
  • A mismatched formatting verb may produce diagnostics rather than the intended value.

Try it yourself

Add a boolean with %t and print the type of amount with %T.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which function returns a formatted string instead of printing it?
Choose one answer. You can try again.

Answer and explanation

fmt.Sprintf

Correct. Printf substitutes the name and two-decimal amount.

What you should remember

You have practiced The fmt Package in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: The strings Package →