Go 如何打印调试深层或嵌套的结构体

前言

在 Go 开发中,遇到多层嵌套的结构体、map、slice 时,fmt.Println 的输出往往一团乱,很难快速看清结构。

下面介绍两个轻量好用的打印包,用简单代码示例帮你快速上手。

1. k0kubun/pp ------ 彩色美观打印

安装:

bash 复制代码
go get github.com/k0kubun/pp/v3

完整示例代码:

go 复制代码
package main

import (
    "github.com/k0kubun/pp/v3"
)

type Profile struct {
    City string
    Job  string
}

type User struct {
    Name    string
    Age     int
    Hobbies []string
    Profile Profile
}

func main() {
    u := User{
        Name:    "张三",
        Age:     28,
        Hobbies: []string{"游泳", "读书", "旅行"},
        Profile: Profile{
            City: "北京",
            Job:  "程序员",
        },
    }

    pp.Println(u)
}

输出效果(终端带颜色显示):

复制代码
{
  Name:    "张三",
  Age:     28,
  Hobbies: ["游泳", "读书", "旅行"],
  Profile: {
    City: "北京",
    Job:  "程序员"
  }
}

个性化配置示例:

go 复制代码
// 全局配置
pp.Default.SetColoringEnabled(false) // 关闭颜色
pp.Default.SetExportedOnly(true)     // 只显示导出字段
pp.Default.SetOmitEmpty(true)        // 省略空值

// 或者创建独立实例
mypp := pp.New()
mypp.SetColoringEnabled(false)
mypp.Println(u)

2. gookit/goutil/dump ------ 功能丰富调试打印

安装:

bash 复制代码
go get github.com/gookit/goutil/dump

完整示例代码:

go 复制代码
package main

import "github.com/gookit/goutil/dump"

type Profile struct {
    City string
    Job  string
}

type User struct {
    Name    string
    Age     int
    Hobbies []string
    Profile Profile
}

func main() {
    u := User{
        Name:    "李四",
        Age:     30,
        Hobbies: []string{"跑步", "游戏", "健身"},
        Profile: Profile{
            City: "上海",
            Job:  "产品经理",
        },
    }

    dump.P(u)
}

输出效果(清晰缩进):

复制代码
User{
    Name: "李四",
    Age: 30,
    Hobbies: []string{"跑步", "游戏", "健身"},
    Profile: Profile{
        City: "上海",
        Job: "产品经理"
    }
}

个性化配置示例:

go 复制代码
dump.Config(func(opts *dump.Options) {
    opts.NoColor = true      // 关闭颜色
    opts.IndentLen = 4       // 缩进空格数
    opts.MaxDepth = 10       // 最大嵌套深度
    opts.SkipPrivate = true  // 跳过私有字段
    opts.SkipNilField = true // 跳过 nil 字段
})

dump.P(u)

总结推荐

  • 想简单快速看结构 → 用 dump.P(v)
  • 想要彩色高亮好看 → 用 pp.Println(v)
相关推荐
ydjs678899-bot24 分钟前
您的Next.js中间件匹配器配置可能会跳过您认为它保护的路由
开发语言·javascript·中间件
Chengbei1132 分钟前
JsOwl|AI 赋能 JS 敏感信息扫描器,AST + 正则、source‑map 源码还原、登录态爬虫输出交互式 HTML 报告
开发语言·javascript·网络·人工智能·爬虫·网络安全·自动化
David猪大卫34 分钟前
【C++修炼】string类:string类的模拟实现
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
geovindu36 分钟前
rust: Iterator Pattern
开发语言·后端·设计模式·rust·行为模式·迭代器模
tianbin9111 小时前
大模型API中转站选型观察:词元无忧API为何值得优先评估
后端
SDWAN_Cheap1 小时前
深度解析什么是CDN加速:从原理到实践的技术拆解
开发语言·cdn加速
鬼手点金1 小时前
模型即 Agent:当模型本身成为产品
开发语言·前端·人工智能·python·机器学习
雨中飘荡的记忆1 小时前
Hooks 怎么用?5 个能直接抄的自动化配置
后端
卷无止境1 小时前
Python 3.14 自由线程:拆掉 GIL 之后,我们到底得到了什么
后端·python
染指11101 小时前
147.Agent-LangGraph归并函数
开发语言·人工智能·python·langchain·agents