Go实战--golang中使用go-spew(davecgh/go-spew)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangshubo1989/article/details/78674248

生命不止,继续 go go go !!!

花絮:
一系列的事儿,开始想想未来如何,要不要离开北京。利用周末,去了趟南京,感觉很好。
我的csdn博客uv访问量如下:
这里写图片描述

—————————————————-悲伤的分割线————————————————–

今天跟大家一起分享一个golang的第三方库go-spew。

go-spew

Implements a deep pretty printer for Go data structures to aid in debugging

简介:
Go-spew implements a deep pretty printer for Go data structures to aid in debugging. A comprehensive suite of tests with 100% test coverage is provided to ensure proper functionality. See test_coverage.txt for the gocov coverage report. Go-spew is licensed under the liberal ISC license, so it may be used in open source or commercial projects.

github地址:
https://github.com/davecgh/go-spew

Star: 1688

文档地址:
https://godoc.org/github.com/davecgh/go-spew/spew

获取:
go get -u github.com/davecgh/go-spew/spew

dump a variable:

spew.Dump(myVar1, myVar2, ...)
spew.Fdump(someWriter, myVar1, myVar2, ...)
str := spew.Sdump(myVar1, myVar2, ...)

应用

spew.Dump

package main

import (
    "github.com/davecgh/go-spew/spew"
)

type Project struct {
    Id      int64  `json:"project_id"`
    Title   string `json:"title"`
    Name    string `json:"name"`
    Data    string `json:"data"`
    Commits string `json:"commits"`
}

func main() {

    o := Project{Name: "hello", Title: "world"}
    spew.Dump(o)
}

输出:

(main.Project) {
 Id: (int64) 0,
 Title: (string) (len=5) "world",
 Name: (string) (len=5) "hello",
 Data: (string) "",
 Commits: (string) ""
}

spew.Printf

package main

import (
    "github.com/davecgh/go-spew/spew"
)

func main() {

    ui8 := uint8(5)
    pui8 := &ui8
    ppui8 := &pui8

    // Create a circular data type.
    type circular struct {
        ui8 uint8
        c   *circular
    }
    c := circular{ui8: 1}
    c.c = &c

    // Print!
    spew.Printf("ppui8: %v\n", ppui8)
    spew.Printf("circular: %v\n", c)
}

输出:

ppui8: <**>5
circular: {1 <*>{1 <*><shown>}}

spew.ConfigState

package main

import (
    "github.com/davecgh/go-spew/spew"
)

func main() {

    scs := spew.ConfigState{Indent: "\t"}

    // Output using the ConfigState instance.
    v := map[string]int{"one": 1}
    scs.Printf("v: %v\n", v)
    scs.Dump(v)
}

输出:

v: map[one:1]
(map[string]int) (len=1) {
    (string) (len=3) "one": (int) 1
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/wangshubo1989/article/details/78674248
go