Stage 1 · Code
Testing & Debugging in Go
Delve Debugger
Set breakpoints, inspect variables, trace goroutines, and step through code with Go's purpose-built debugger.
Installing Delve
Delve (dlv) is the standard Go debugger. It understands goroutines, deferred functions, and Go's calling conventions in a way that generic debuggers like gdb do not.
go install github.com/go-delve/delve/cmd/dlv@latest
dlv versionStarting a Debug Session
| Command | When to use |
|---|---|
dlv debug ./cmd/myapp | Build and debug in one step (most common) |
dlv test ./pkg | Debug a specific test package |
dlv exec ./myapp | Debug an already-built binary |
dlv attach <pid> | Attach to a running process |
dlv connect :2345 | Connect to a headless Delve server |
# Debug the main package
dlv debug .
# Debug a test
dlv test ./internal/task -- -run TestAdd
# VS Code: launch.json (press F5)
# {
# "type": "go",
# "request": "launch",
# "program": "${workspaceFolder}/cmd/myapp"
# }Breakpoints and Stepping
Set a breakpoint at a file:line or a function name. Once paused, step through code one line at a time or step into function calls.
(dlv) break main.main # breakpoint at function
(dlv) break main.go:42 # breakpoint at line
(dlv) continue # run until next breakpoint (alias: c)
(dlv) next # step over (next line, alias: n)
(dlv) step # step into function call (alias: s)
(dlv) stepout # finish current function and return
(dlv) list # show current source location
(dlv) clearall # remove all breakpointsInspecting State
Once paused at a breakpoint, inspect variables, evaluate expressions, and examine goroutines without modifying any code.
(dlv) locals # all local variables
(dlv) print variableName # print a specific variable (alias: p)
(dlv) print myMap["key"] # evaluate expressions
(dlv) whatis variableName # show the type of a variable
(dlv) goroutines # list all goroutines
(dlv) goroutine 3 # switch to goroutine 3
(dlv) stack # current goroutine stack trace
(dlv) frame 2 # switch to stack frame 2
(dlv) watch -w myVar # watchpoint: break when myVar changesThe Go extension for VS Code integrates Delve seamlessly. Set breakpoints by clicking the gutter, press F5 to start debugging, and use the Variables panel instead of typing print. This is faster for most debugging sessions than the command-line interface.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.