实现说明
活动部件是函数 countShapes、main。
重复被限制在 for _, child := range t 里——其余代码按顺序各跑一遍。失败处理就是 panic(err):1 个检查点在问题出现的地方中止程序。
使用要点
panic(err)是这里唯一的失败路径:第一个问题就会终止程序。- 直接运行文件,输出会带上标签,比如
objects=、replicas:——输出的每一行都能指回产生它的那次调用。 - 运行整个文件:
main会依次驱动countShapes。
常见问题
调用方该如何处理失败?
以终止运行上报:1 处检查都会触发 panic(err),调用方看到的失败就是程序停下。
运行「JSON 解码进 any 值树」会打印什么?
整个文件跑完,输出行以 objects=、replicas: 这类前缀开头。
签名一览:func countShapes(v any) (objects, arrays, numbers, strings int)
核心语句
for _, child := range t {
o, a, n, s := countShapes(child)
objects, arrays, numbers, strings = objects+o, arrays+a, numbers+n, strings+s
}
代码示例
package main
import (
"encoding/json"
"fmt"
)
// countShapes walks the decoded tree and counts what it finds.
func countShapes(v any) (objects, arrays, numbers, strings int) {
switch t := v.(type) {
case map[string]any:
objects++
for _, child := range t {
o, a, n, s := countShapes(child)
objects, arrays, numbers, strings = objects+o, arrays+a, numbers+n, strings+s
}
case []any:
arrays++
for _, child := range t {
o, a, n, s := countShapes(child)
objects, arrays, numbers, strings = objects+o, arrays+a, numbers+n, strings+s
}
case float64:
numbers++
case string:
strings++
}
return objects, arrays, numbers, strings
}
func main() {
payload := `{"service":"billing","replicas":3,"tags":["prod","eu"],"meta":{"queue":"jobs"}}`
// Unmarshal into any: objects decode to map[string]any, numbers to float64
var tree map[string]any
if err := json.Unmarshal([]byte(payload), &tree); err != nil {
panic(err)
}
fmt.Printf("%T with %d keys\n", tree, len(tree))
objs, arrs, nums, strs := countShapes(tree)
fmt.Printf("objects=%d arrays=%d numbers=%d strings=%d\n", objs, arrs, nums, strs)
// type assertion reaches into one branch of the tree
replicas, ok := tree["replicas"].(float64)
fmt.Println("replicas:", replicas, "present:", ok)
}