关于golang:Mix-XFMT-解决-Golang-结构体嵌套格式化打印指针地址

6次阅读

共计 1150 个字符,预计需要花费 3 分钟才能阅读完成。

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/

正文完
 0