You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言如何打印包含值类型信息的map[string]interface{}嵌套结构

解决方案

你可以通过递归遍历嵌套的map[string]interface{}结构,批量打印每个键的路径、对应值和类型,不需要手动逐个处理。

实现代码

package main

import (
	"fmt"
)

// PrintMapWithType 递归打印嵌套map的键、值、类型,prefix用于拼接嵌套层级的键路径
func PrintMapWithType(m map[string]interface{}, prefix string) {
	for k, v := range m {
		fullKey := prefix + k
		// 判断当前值是不是嵌套的map[string]interface{}
		if nestedMap, ok := v.(map[string]interface{}); ok {
			fmt.Printf("%s: (map[string]interface{})\n", fullKey)
			// 递归处理嵌套map,前缀加当前键和点,方便看层级
			PrintMapWithType(nestedMap, fullKey+".")
			continue
		}
		// 普通值直接打印键、值、类型
		fmt.Printf("%s: %v (type: %T)\n", fullKey, v, v)
	}
}

func main() {
	m := map[string]interface{}{
		"one": uint16(1), "two": map[string]interface{}{
			"three": uint32(3), "four": uint64(4),
		},
	}
	PrintMapWithType(m, "")
}

输出效果

one: 1 (type: uint16)
two: (map[string]interface{})
two.three: 3 (type: uint32)
two.four: 4 (type: uint64)

扩展适配

如果你的嵌套结构里还有其他复合类型(比如切片、数组),可以在判断分支里新增对应类型的递归逻辑即可。

内容的提问来源于stack exchange,提问作者user17503953

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 03:06:03