Nil Versus Empty Slices In JSON

Nil slices marshal to null, empty slices to []; both append and iterate identically, and omitempty drops either because a length-zero slice counts as empty.

GoData Integrity

Code

gosnippet
34 lines
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":[]}
}

What runs when

Nil Versus Empty Slices In JSON is built around the function main.

Applying it

Running the file prints labeled results such as nil ->, empty ->, same len: — each operation’s effect is visible in the output.

Statements that matter

nilTags = append(nilTags, "go")

Interactive Tools for This Topic

FAQ

What does Nil Versus Empty Slices In JSON print when run?
No setup needed: run the file and look for labeled lines like `nil ->`, `empty ->`, `same len:` in the output.