go - 如何将地址转换为类型并在 GDB for Golang 中打印它

标签 go gdb

这是一段代码:

package main

import (
    "fmt"
)

type TestType struct {
    a int
    b int
}

func main() {
    var testType TestType = TestType{1, 2}
    fmt.Println(testType)
}

这是 gdb 调试输出:

(gdb) r
Starting program: /home/bzhang/common/src/go/src/test/testBinary 

Breakpoint 1, main.main () at /home/bzhang/common/src/go/src/test/main.go:14
14              fmt.Println(testType)
(gdb) p testType
$1 = {a = 1, b = 2}
(gdb) p &testType
$2 = (main.TestType *) 0xc820059ee8
(gdb) p ('main.TestType'*) 0xc820059ee8
A syntax error in expression, near `) 0xc820059ee8'.
(gdb) p ('TestType'*) 0xc820059ee8     
A syntax error in expression, near `) 0xc820059ee8'.
(gdb) whatis testType
type = main.TestType
(gdb) 

我当然知道可以直接打印testType。但是如果是局部变量,有时不能直接打印出它的值,只能得到它的地址。所以我想用它的类型来打印它的值。但它似乎无法正常工作。 感谢您的帮助!

最佳答案

delve 工具比 gdb 好。 https://github.com/go-delve/delve

  1. 安装 delve
go get -u github.com/go-delve/delve/cmd/dlv
  1. 在 main.go 上移动路径
cd $GOPATH/src/YOUPROJECT/main.go
  1. 调试钻研
$GOPATH/bin/delve debug main.go
  1. 主要断点
Type 'help' for list of commands.
(dlv) b main.main
Breakpoint 1 set at 0x4a7bbf for main.main() main.go:12
  1. 运行
(dlv) c
> main.main() main.go:12 (hits goroutine(1):1 total:1) (PC: 0x4a7bbf)
     7: type TestType struct {
     8:         a int
     9:         b int
    10: }
    11:
=>  12: func main() {
    13:         var testType TestType = TestType{1, 2}
    14:         fmt.Println(testType)
    15: }
  1. 断点14行
(dlv) b 14
Breakpoint 2 set at 0x4a7bf0 for main.main() main.go:14
  1. 继续
(dlv) c
> main.main() main.go:14 (hits goroutine(1):1 total:1) (PC: 0x4a7bf0)
     9:         b int
    10: }
    11:
    12: func main() {
    13:         var testType TestType = TestType{1, 2}
=>  14:         fmt.Println(testType)
    15: }
  1. 显示值(value)
(dlv) locals
testType = main.TestType {a: 1, b: 2}

最后使用goland,vscode调试更方便。

关于go - 如何将地址转换为类型并在 GDB for Golang 中打印它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40882206/

相关文章:

go - 如何创建字节矩阵Golang

mono - 改进GDB宏

python - 如何在 virtualenv 中使用 gdb python 调试扩展

c++ - 使用 Visual Studio 代码进行远程调试(C++)

sqlite - 如何从配置文件获取路径

go - 包装结构引用

postgresql - Golang Postgres 连接字符串未打开返回 null

golang 1.2 : Unzip password protected zip file?

c - gdb 远程调试。实现一个伪造的 gdbserver stub 。经过多次请求和响应,得到警告 :invalid remote reply

c - GDB 无法识别某些 C 函数