美文网首页
Mix XFMT 解决 Golang 结构体嵌套格式化打印指针地

Mix XFMT 解决 Golang 结构体嵌套格式化打印指针地

作者: 撸代码的乡下人 | 来源:发表于2020-12-25 11:44 被阅读0次

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/

相关文章

  • Mix XFMT 解决 Golang 结构体嵌套格式化打印指针地

    OpenMix 出品:https://openmix.org[https://openmix.org/mix-go...

  • 结构体的基本操作

    结构体定义和初始化 结构体变量相互赋值 结构体数组 结构体嵌套一级指针 结构体嵌套二级指针 结构体偏移量 联合体 ...

  • 结构体

    结构体初识 结构体指针 结构体的匿名字段 结构体嵌套 Go语言中的OOP

  • protoc-生成go指针

    protoc-生成go指针 这里指的是为结构体中基础类型生成go指针,嵌套结构体默认就是指针 为什么需要生成指针?...

  • Golang 指针和结构体

    Golang 指针和结构体 于c语言相同,go中也有指针和结构体的概念。指针表示变量的内存地址,结构体用来存储同一...

  • 【Golang】json自定义序列化的深入解析

    对于使用结构体中嵌套结构体的情况,只有receiver为指针类型,而嵌套结构体为结构体的值语义的时候不能触发自定义...

  • Golang结构体和指针

    Golang是一门很特殊的语言,虽然它出生比较晚,但是在很多地方却和现在的编程语言有所不同。现在的编程语言要么是函...

  • 结构体嵌套

    结构体嵌套 结构体嵌套时应逐级引用

  • C语言20 结构体指针

    C语言20 结构体指针 探测结构体指针的特性 ++、-- 加法与减法 指针相减 使用结构体指针 结构体指针一定要指...

  • 结构体嵌套

    普通结构体嵌套 普通结构体嵌套,嵌套结构体可以通过 .子变量.方法 的方式获取被嵌套的属性和方法 匿名嵌套 匿名嵌...

网友评论

      本文标题:Mix XFMT 解决 Golang 结构体嵌套格式化打印指针地

      本文链接:https://www.haomeiwen.com/subject/aimbnktx.html