如何漂亮地打印变量 [英] How to pretty print variables

查看:79
本文介绍了如何漂亮地打印变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go中是否有Ruby的awesome_print之类的东西?

Is there something like Ruby's awesome_print in Go?

例如在Ruby中,您可以编写:

For example in Ruby you could write:

require 'ap'
x = {a:1,b:2} // also works for class
ap x

输出为:

{ 
  "a" => 1,
  "b" => 2
}

我能找到的最接近的东西是Printf("%#v", x)

closest thing that I could found is Printf("%#v", x)

推荐答案

如果您的目标是避免导入第三方程序包,则另一个选择是使用json.MarshalIndent :

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))

输出:

{
    "a": 1,
    "b": 2
}

工作示例: http://play.golang.org/p/SNdn7DsBjy

这篇关于如何漂亮地打印变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆