英文:
How to pretty print variables
问题
在Go语言中是否有类似Ruby的awesome_print
的功能?
例如,在Ruby中,你可以这样写:
require 'ap'
x = {a:1,b:2} // 也适用于类
ap x
输出结果将会是:
{
"a" => 1,
"b" => 2
}
在Go语言中,最接近的功能是使用Printf("%#v", x)
。
英文:
Is there something like Ruby's awesome_print
in Go?
For example in Ruby you could write:
require 'ap'
x = {a:1,b:2} // also works for class
ap x
the output would be:
{
"a" => 1,
"b" => 2
}
closest thing that I could found is Printf("%#v", x)
答案1
得分: 122
如果你的目标是避免导入第三方包,另一个选择是使用 json.MarshalIndent:
x := map[string]interface{}{"a": 1, "b": 2}
b, err := json.MarshalIndent(x, "", " ")
if err != nil {
fmt.Println("error:", err)
}
fmt.Print(string(b))
输出:
{
"a": 1,
"b": 2
}
工作示例:http://play.golang.org/p/SNdn7DsBjy
英文:
If your goal is to avoid importing a third-party package, your other option is to use json.MarshalIndent:
x := map[string]interface{}{"a": 1, "b": 2}
b, err := json.MarshalIndent(x, "", " ")
if err != nil {
fmt.Println("error:", err)
}
fmt.Print(string(b))
Output:
{
"a": 1,
"b": 2
}
Working sample: http://play.golang.org/p/SNdn7DsBjy
答案2
得分: 27
没问题,以下是翻译好的内容:
不用担心,我找到一个:https://github.com/davecgh/go-spew
// 导入 "github.com/davecgh/go-spew/spew" 包
x := map[string]interface{}{"a":1,"b":2}
spew.Dump(x)
输出结果如下:
(map[string]interface {}) (len=2) {
(string) (len=1) "a": (int) 1,
(string) (len=1) "b": (int) 2
}
英文:
Nevermind, I found one: https://github.com/davecgh/go-spew
// import "github.com/davecgh/go-spew/spew"
x := map[string]interface{}{"a":1,"b":2}
spew.Dump(x)
Would give an output:
(map[string]interface {}) (len=2) {
(string) (len=1) "a": (int) 1,
(string) (len=1) "b": (int) 2
}
答案3
得分: 14
如果你想要漂亮的彩色输出,你可以使用 pp
。
import "github.com/k0kubun/pp"
...
pp.Print(m)
英文:
If you want pretty coloured output, you can use pp
.
import "github.com/k0kubun/pp"
...
pp.Print(m)
答案4
得分: 4
我刚刚根据Simon的答案编写了一个简单的函数:
func dump(data interface{}) {
b, _ := json.MarshalIndent(data, "", " ")
fmt.Print(string(b))
}
这个函数的作用是将数据转换为JSON格式并打印出来。
英文:
I just wrote a simple function based on Simons answer:
func dump(data interface{}){
b,_:=json.MarshalIndent(data, "", " ")
fmt.Print(string(b))
}
答案5
得分: 3
我来帮你翻译:
我想使用这样的代码片段:
func printMap(m map[string]string) {
var maxLenKey int
for k, _ := range m {
if len(k) > maxLenKey {
maxLenKey = len(k)
}
}
for k, v := range m {
fmt.Println(k + ": " + strings.Repeat(" ", maxLenKey - len(k)) + v)
}
}
输出将会是这样的:
short_key: value1
really_long_key: value2
告诉我,是否有更简单的方法来实现相同的对齐效果。
英文:
I came up to use snippet like this:
func printMap(m map[string]string) {
var maxLenKey int
for k, _ := range m {
if len(k) > maxLenKey {
maxLenKey = len(k)
}
}
for k, v := range m {
fmt.Println(k + ": " + strings.Repeat(" ", maxLenKey - len(k)) + v)
}
}
The output will be like this:
short_key: value1
really_long_key: value2
Tell me, if there's some simpler way to do the same alignment.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论