How to pretty print variables

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


I just wrote a simple function based on Simons answer:

func dump(data interface{}){
    b,_:=json.MarshalIndent(data, "", "  ")
    fmt.Print(string(b))
}

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
}

If you want pretty coloured output, you can use pp.

https://github.com/k0kubun/pp

import "github.com/k0kubun/pp"
...
pp.Print(m)

pp preview