MixGo XFMT 解決 Golang 結構體巢狀格式化列印指標地址
阿新 • • 發佈:2020-12-26
OpenMix 出品:https://openmix.org
Mix XFMT
可以列印結構體巢狀指標地址內部資料的格式化庫
Formatting library that can print the internal data of the nested pointer address of the struct
Github
https://github.com/mix-go/xfmt
Overview
在 Golang 中使用 fmt
列印結構體時,無法列印指標欄位內部的資料結構,導致增加 debug 難度,該庫可以解決這個問題。
Installation
- 安裝
go get -u github.com/mix-go/xfmt
Usage
-
支援的方法,與
fmt
系統庫完全一致Sprintf(format string, args ...interface{}) string
Sprint(args ...interface{}) string
Sprintln(args ...interface{}) string
Printf(format string, args ...interface{})
Print(args ...interface{})
Println(args ...interface{})
-
支援
Tag
忽略某個引用欄位
type Foo struct { Bar *Bar `xfmt:"-"` }
- 使用
包含指標的結構體
type Level3 struct {
Name string
}
type Level2 struct {
Level3 *Level3 `xfmt:"-"`
Name string
}
type Level1 struct {
Name string
Level2 *Level2
Level2_1 *Level2
}
建立變數
l3 := Level3{Name: "Level3"} l2 := Level2{Name: "Level2", Level3: &l3} l1 := Level1{Name: "Level1", Level2: &l2, Level2_1: &l2}
列印對比
fmt
列印
fmt.Println(fmt.Sprintf("%+v", l1))
{Name:Level1 Level2:0xc00009c500 Level2_1:0xc00009c500}
xfmt
列印:其中 Level3 被定義的 tag 忽略,Level2_1 由於和 Level2 是同一個指標因此後面的忽略處理
fmt.Println(xfmt.Sprintf("%+v", l1))
{Name:Level1 Level2:0xc00009c500:&{Level3:0xc00007f030 Name:Level2} Level2_1:0xc00009c500}
License
Apache License Version 2.0, http://www.apache.org/licenses/