以下是在Debian中调试Golang程序的常用技巧及工具:
Delve(推荐)
go get -u github.com/go-delve/delve/cmd/dlvdlv debug ./main.gobreak <文件:行号/函数>:设置断点continue/c:继续执行至断点next/n:单步执行(不进入函数)step/s:单步执行(进入函数)print <变量名>:查看变量值set <变量名>=<值>:修改变量值。GDB
sudo apt-get install gdbgo build -gcflags "-N -l" -o debug-program main.gobreak <函数/行号>:设置断点run:启动程序next/step:单步执行print <变量名>:查看变量。IDE集成调试
launch.json后按F5启动调试,支持断点、变量查看等。日志记录
log或第三方库(如logrus)输出关键信息,定位执行流程问题。log.Println("当前变量值:", variable)。性能分析
import _ "net/http/pprof",启动HTTP服务后通过go tool pprof分析CPU/内存。go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30。单元测试
testing包编写测试用例,通过go test快速验证代码逻辑。func TestAdd(t *testing.T) {
if Add(1, 2) != 3 {
t.Error("加法错误")
}
}
编译优化
go build -gcflags="-N -l",避免代码被优化导致调试信息不准确。以上工具和方法可组合使用,根据具体需求选择最适合的调试方案。