Delve is a powerful debugger specifically designed for the Go programming language. It provides developers with essential debugging capabilities, such as setting breakpoints, stepping through code, inspecting variables, and more. Delve integrates seamlessly with various editors and IDEs, making it an indispensable tool for Go developers.
To install Delve, use the following command:
shgo install github.com/go-delve/delve/cmd/dlv@latest
Start Debugging a Package
shdlv debug [package]
This command compiles the specified package and starts a debugging session.
Example:
shdlv debug main.go
Attach to a Running Process
shdlv attach [pid]
This command attaches Delve to a running Go process specified by its process ID (PID).
Example:
shdlv attach 12345
Navigate to Your Project Directory
shcd path/to/your/project
Start Delve Debugger
shdlv debug main.go
This command will compile main.go
and start the Delve debugger.
Once in the Delve interactive session, you can set breakpoints at specific lines or functions.
Set a Breakpoint at a Line
sh(dlv) break main.go:10
Set a Breakpoint at a Function
sh(dlv) break main.main
Continue Execution
sh(dlv) continue
Step Into a Function
sh(dlv) step
Step Over a Line
sh(dlv) next
Step Out of the Current Function
sh(dlv) stepout
Print a Variable
sh(dlv) print variableName
List Local Variables
sh(dlv) locals
List Function Arguments
sh(dlv) args
List All Breakpoints
sh(dlv) breakpoints
Clear a Breakpoint
sh(dlv) clear breakID
Here is an example of a typical debugging session using Delve:
Start Delve Debugger
shdlv debug main.go
Set a Breakpoint at the main
Function
sh(dlv) break main.main
Start Program Execution
sh(dlv) continue
Step Through Code
sh(dlv) next
Inspect a Variable
sh(dlv) print myVar
Continue Execution
sh(dlv) continue
End Debugging Session
sh(dlv) exit
Delve is an essential tool for Go developers, providing robust debugging capabilities that integrate well with various development environments. By mastering Delve, you can significantly improve your ability to identify and fix issues in your Go programs, leading to more efficient and effective development workflows.