← 中文资源

简体中文版本

解码记录按数值字段排序

先解码 JSON 记录数组,按数值字段用 slices.SortFunc 排序再重新编码:报表输出不再依赖上游给的顺序,字段与标签原样保留。

阅读英文原文

实现说明

解码记录按数值字段排序的核心是函数 main。 错误处理是内联的:2 处测试 err != nil 并立即分支。

使用要点

  • 直接运行文件,输出会带上标签,比如 decode failed:、encode failed:、sorted:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「解码记录按数值字段排序」会打印什么?

整个文件跑完,输出行以 decode failed:、encode failed:、sorted: 这类前缀开头。

核心语句

if err != nil {
	fmt.Println("encode failed:", err)
	return
}
return cmp.Compare(b.Score, a.Score)

代码示例

package main

import (
	"cmp"
	"encoding/json"
	"fmt"
	"slices"
)

// Decoded records arrive in arbitrary order; sort by the numeric field before reporting.
type Record struct {
	User  string  `json:"user"`
	Score float64 `json:"score"`
}

func main() {
	payload := `[
		{"user":"ana","score":81.5},
		{"user":"bob","score":97},
		{"user":"cid","score":72.25}
	]`

	var records []Record
	if err := json.Unmarshal([]byte(payload), &records); err != nil {
		fmt.Println("decode failed:", err)
		return
	}

	// 数值字段降序:b 在前 a 在后即为逆序
	slices.SortFunc(records, func(a, b Record) int {
		return cmp.Compare(b.Score, a.Score)
	})

	out, err := json.Marshal(records)
	if err != nil {
		fmt.Println("encode failed:", err)
		return
	}
	fmt.Println("sorted:", string(out))
}