59

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)

2

5 Answers 5

120

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

3
  • 1
    Testing multiple levels of indention. play.golang.org/p/d3nO4Rht90
    – Xeoncross
    Dec 19, 2016 at 15:23
  • 1
    Marshal gets intro trouble when there is a custom struct (unsupported type error). Any easy way to fix that?
    – etang
    Aug 9, 2017 at 0:18
  • @etang You would have to show a simple example for me to give you a better answer (perhaps in the Playground?). I imagine you'll have to implement one of the JSON package interfaces for unmarshalling your type if it becomes complex. Aug 9, 2017 at 0:40
26

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
}
11

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

1
  • 1
    good one for pretty print
    – Krishna ps
    Dec 12, 2021 at 9:40
3

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.

1
  • 4
    You can use fmt.Printf("%*s: %s", maxLenKey, k, v) to avoid the strings.Repeat call and all that concatenation. Nov 11, 2018 at 8:24
3

I just wrote a simple function based on Simons answer:

func dump(data interface{}){
    b,_:=json.MarshalIndent(data, "", "  ")
    fmt.Print(string(b))
}
1
  • I do this all the time, +1. though I usually panic on the error
    – erik258
    Feb 24, 2022 at 3:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.