gopretty-print

How to pretty print variables


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)


Solution

  • 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