← 中文资源

简体中文版本

nil 切片与空切片的 JSON 差异

nil 切片编码成 null、空切片编码成 [];两者 len 相同、append 与 range 都安全。omitempty 按长度判空(encoding/json 把空切片视为 empty value),nil 与 [] 都会被省略——要在 API 契约里区分两者,需去掉 omitempty 或自定义 MarshalJSON。

阅读英文原文

实现说明

nil 切片与空切片的 JSON 差异的核心是函数 main。

使用要点

  • 跑完文件,输出里会留下标记——nil ->、empty ->、same len:。

常见问题

运行「nil 切片与空切片的 JSON 差异」会打印什么?

运行文件本身,nil ->、empty ->、same len: 这些前缀各对应一段演示逻辑。

核心语句

nilTags = append(nilTags, "go")

代码示例

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	// nil 切片:var 声明的零值,没有底层数组
	var nilTags []string
	emptyTags := []string{}

	nilJSON, _ := json.Marshal(nilTags)
	emptyJSON, _ := json.Marshal(emptyTags)
	fmt.Printf("nil -> %s\n", nilJSON) // null
	fmt.Printf("empty -> %s\n", emptyJSON)

	// 运行时行为一致:len 相同、append 与 range 都安全
	fmt.Println("same len:", len(nilTags) == len(emptyTags))
	nilTags = append(nilTags, "go")
	fmt.Println("nil usable after append:", nilTags)

	// omitempty 按长度判空:encoding/json 把 empty value 定义为
	// "any array, slice, map, or string of length zero"——nil 与 []
	// 都会被省略,不做 nil 与空切片的区分。
	// tags 带 omitempty 从输出里消失;roles 不带,空切片照样输出 []
	resp := struct {
		Name  string   `json:"name"`
		Tags  []string `json:"tags,omitempty"`
		Roles []string `json:"roles"`
	}{Name: "svc", Tags: emptyTags, Roles: []string{}}
	out, _ := json.Marshal(resp)
	fmt.Println(string(out)) // {"name":"svc","roles":[]}
}