Empty slices and json.Marshall

There are two ways to initialize an empty slice in go:

var A = []string{}
var B []string

I would like to understand why these two are considered syntactically equivalent (or are they not?) when built-in libs like encoding/json in methods like Marshall output different values each respective case.

I might be missing some key idea on the compiler or the design choice but I would appreciate if someone could shed some light on this :slight_smile:

Here’s a piece of code you can run on https://play.golang.org/:

package main

import (
	"fmt"
	"encoding/json"
)

func main() {
	var A = []string{}
	var B []string
	msgA, errA := json.Marshal(A)
	msgB, errB := json.Marshal(B)
	fmt.Printf("%v; %v\n", string(msgA), errA)
	fmt.Printf("%v; %v\n", string(msgB), errB)
}

There is indeed a difference: A gets initialized as an empty slice, whereas B is a nil slice. This becomes apparent when printing the two variables with a “%#v” format string:

https://play.golang.org/p/C3eg22p4IT

1 Like

In general your var B []string is more semantically like var B []string = nil or var B = []string(nil).

var X type always initializes with the zero value.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.