How to pretty print variables

前端 未结 3 700
执念已碎
执念已碎 2020-12-13 06:25

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         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-13 06:41

    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

提交回复
热议问题