Duplicate map keys

September 25, 2023

It’s Monday again. That means I’ll be live-coding again! I hope you can join me.


Composite literals

… For map literals, all elements must have a key. It is an error to specify multiple elements with the same field name or constant key value. For non-constant map keys, see the section on evaluation order.

I expect we can all agree this makes sense. Keys in a map literal must be unique.

var animals = map[string]string{
	"cow":  "moo",
	"duck": "quack",
	"pig":  "oink",
	"cow":  "moo2", // invalid: duplicate key "cow" in map literal
}

But there’s an exception… Keys in a map literal aren’t required to be constants. And if you use a non-constant map key, as in the below example, you can end up with duplicate keys, in which case the evaluation order rules apply to determine which value will apply:

var cow = "cow"
var animals = map[string]string{
	"cow":  "moo",
	"duck": "quack",
	"pig":  "oink",
	cow:    "moo2", // Non-constant duplicate key allowed, but only one value takes effect
}
fmt.Println(animals) // Prints: map[cow:moo2 duck:quack pig:oink]

Quotes from The Go Programming Language Specification Version of August 2, 2023


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe