ProgramGuru

Code Formatting with gofmt

Start with Code Formatting with gofmt

In this lesson, explore code formatting with gofmt through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of code formatting with gofmt.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

gofmt applies Go’s standard formatting conventions. Run gofmt -w filename.go to rewrite files or gofmt -d filename.go to inspect changes.

Consistent formatting helps reviews focus on behavior. gofmt does not guarantee correct logic or detect every programming error.

Visualize how it works

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

Visual explanation for gofmtGo provides an opinionated, common source format.Write codeStep 1Run gofmtStep 2Review diffStep 3Commit consistent styleStep 4Go provides an opinionated, common source format.
Go provides an opinionated, common source format.

Tools, syntax and practical notes

Use gofmt -w main.go, or run go fmt ./... for packages in the module.

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() {
	numbers := []int{1, 2, 3}
	fmt.Println("Total:", numbers[0]+numbers[1]+numbers[2])
}

Output

Total: 6

Trace what the program does

The code formats with gofmt and computes 6. Whitespace and indentation changes do not alter the calculation.

Avoid common mistakes

  • Do not manually align code in ways that fight gofmt.
  • Formatting is not static analysis or unit testing.

Try it yourself

Run gofmt -d on a deliberately misindented copy and compare the proposed changes.

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

Check your understanding

What does gofmt primarily do?
Choose one answer. You can try again.

Answer and explanation

Normalize source code formatting

Correct. The code formats with gofmt and computes 6.

What you should remember

You have practiced Code Formatting with gofmt 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: Static Analysis with go vet →