ProgramGuru

Debugging Go Programs

Start with Debugging Go Programs

In this lesson, explore debugging go programs through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

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

Understand the idea

Debugging means locating where observed behavior differs from the expected behavior. Use small reproductions, useful logs, unit tests, and a debugger such as Delve to inspect execution.

A productive sequence is reproduce, identify the wrong value or branch, form a hypothesis and verify a targeted fix.

Visualize how it works

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

Visual explanation for debuggingDebugging tests an explanation against observed behavior.Reproduce bugStep 1Inspect valuesStep 2Hypothesize causeStep 3Test the fixStep 4Debugging tests an explanation against observed behavior.
Debugging tests an explanation against observed behavior.

Tools, syntax and practical notes

Typical debugger workflow: dlv debug, set a breakpoint, inspect variables, and step through code. Delve is a separate development tool; it is not bundled with the Go standard library. See Delve.

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 average(total, count int) float64 {
	if count == 0 {
		return 0
	}
	return float64(total) / float64(count)
}
func main() { fmt.Printf("Average: %.1f\n", average(7, 2)) }

Output

Average: 3.5

Trace what the program does

Both integers are converted to float64 before division, so the program prints 3.5. Integer division before conversion would lose the fractional part.

Avoid common mistakes

  • Check intermediate values, not only the final output.
  • Avoid leaving sensitive information in debug logs.

Try it yourself

Change average to intentionally use integer division and write a test that reveals the bug, then fix it.

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

Check your understanding

Why convert operands before dividing?
Choose one answer. You can try again.

Answer and explanation

To preserve the fractional part

Correct. Both integers are converted to float64 before division, so the program prints 3.

What you should remember

You have practiced Debugging Go Programs 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: CPU Profiling →