分享一个工具包:goutil/dump
。这是一个 golang 数据打印工具包,可以打印漂亮易读的 go slice、map、struct 数据。
主要特性有:
dump.P(vars…)
使用简单,直接调用即可效果预览:
output-example
项目地址:https://github.com/gookit/goutil/。
文档:https://pkg.go.dev/github.com/gookit/goutil/dump。
package main
import "github.com/gookit/goutil/dump"
// rum demo:
// go run ./dump/_examples/basic_types.go
func main() {
dump.P(
nil, true,
12, int8(12), int16(12), int32(12), int64(12),
uint(22), uint8(22), uint16(22), uint32(22), uint64(22),
float32(23.78), float64(56.45),
'c', byte('d'),
"string",
)
}
输出:
print-basic
打印数组、切片时,每行输出一个元素,最后输出长度。
package main
import "github.com/gookit/goutil/dump"
// rum demo:
// go run ./dump/_examples/slice.go
func main() {
dump.P(
[]byte("abc"),
[]int{1, 2, 3},
[]string{"ab", "cd"},
[]interface{}{
"ab",
234,
[]int{1, 3},
[]string{"ab", "cd"},
},
)
}
输出:
print-slice
打印 map 数据结构时,每行输出一个元素,最后输出 map 的长度。
package main
import "github.com/gookit/goutil/dump"
// rum demo:
// go run ./map.go
// go run ./dump/_examples/map.go
func main() {
dump.P(
map[string]interface{}{
"key0": 123,
"key1": "value1",
"key2": []int{1, 2, 3},
"key3": map[string]string{
"k0": "v0",
"k1": "v1",
},
},
)
}
输出:
print-map
打印 struct 时,指针类型会自动打印底层真实数据。
package main
import (
"fmt"
"github.com/gookit/color"
"github.com/gookit/goutil/dump"
)
// rum demo:
// go run ./struct.go
// go run ./dump/_examples/struct.go
func main() {
s1 := &struct {
cannotExport map[string]interface{}
}{
cannotExport: map[string]interface{}{
"key1": 12,
"key2": "abcd123",
},
} s2 := struct {
ab string
Cd int
}{
"ab", 23,
}
color.Infoln("- Use fmt.Println:")
fmt.Println(s1, s2)
color.Infoln("\n- Use dump.Println:")
dump.P(
s1,
s2,
)
}
输出:
print-struct
你还可以自定义 dumper 选项,比如缩进和颜色主题:
// Options for dump vars
type Options struct {
// Output the output writer
Output io.Writer
// NoType dont show data type TODO
NoType bool
// NoColor don't with color
NoColor bool
// IndentLen width. default is 2
IndentLen int
// IndentChar default is one space
IndentChar byte
// MaxDepth for nested print
MaxDepth int
// ShowFlag for display caller position
ShowFlag int
// MoreLenNL array/slice elements length > MoreLenNL, will wrap new line
// MoreLenNL int
// CallerSkip skip for call runtime.Caller()
CallerSkip int
// ColorTheme for print result.
ColorTheme Theme
}
觉得不错可以试用,对于调试可能有帮助。
原文链接:https://dev.to/inhere/goutildump-print-beautiful-and-easy-to-read-go-data-504j
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8