How to pretty print variables

前端 未结 3 694
执念已碎
执念已碎 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:37

    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.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-13 06:51

    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
    }
    
    0 讨论(0)
提交回复
热议问题