如何在IntelliJ中调试返回多个值的Go函数?

huangapple go评论71阅读模式
英文:

How to debug a Go function returning multiple values in IntelliJ?

问题

假设我们正在调试一些Go代码,并且在外部依赖中遇到了这行代码:

return json.Marshal(foo)

我们想设置一个断点,并使用IntelliJ的"Evaluate Expression"来检查生成的JSON。然而,这样做是行不通的:

  • 如果我们评估表达式json.Marshal(foo),我们只能看到字节数组。
  • 评估string(json.Marshal(foo))是不起作用的,因为json.Marshal返回两个值,即字节数组和一个错误。
  • 在Go中没有办法直接访问其中一个返回值。

那么,在不能更改底层源代码的情况下,我如何使用"Evaluate Expression"来实现我的目标,即只打印生成的JSON字符串呢?

英文:

Suppose we are debugging some Go code, and somewhere in an external dependency we encounter this line:

return json.Marshal(foo)

We want to set a breakpoint and use IntelliJ's "Evaluate Expression" to inspect the JSON being produced. However, this doesn't work:

  • If we evaluate the expression json.Marshal(foo), we only get to see the byte array.
  • Evaluating string(json.Marshal(foo)) doesn't work because json.Marshal returns two values, the byte array and an error.
  • There is no way in Go to access one of the return values directly.

So how can I use "Evaluate Expression" to achieve my goal of just printing the produced JSON string when I'm not able to change the underlying source code?

答案1

得分: 3

你可以将返回的字节打印为字符串。

bytes, err := json.Marshal(foo)
// 在这里检查错误
fmt.Println(string(bytes))

根据评论进行更新

在不更改源代码的情况下,你无法将字节切片在调试器中更改为字符串。

英文:

you can print the returned bytes as a string

bytes, err := json.Marshal(foo)
// check error here
fmt.Println(string(bytes))

update based on comments

You can't change the byte slice in the debugger to a string without changing the source code.

huangapple
  • 本文由 发表于 2021年11月2日 16:25:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/69807281.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定