Map Slice Values Need Append Write Back

append returns a new slice header, so map values must be written back; a dropped append never shows up in the map regardless of spare capacity.

GoData Integrity

Code

gosnippet
22 lines
package main

import "fmt"

func main() {
	events := map[string][]string{
		"build": {"compile"},
	}

	// append returns a new slice header, so slice values in maps need write-back
	events["build"] = append(events["build"], "link", "package")
	fmt.Println("build:", events["build"])

	// dropped append: whatever the cap allows, the map never sees the value
	sp := events["build"]
	_ = append(sp, "forgotten")
	fmt.Println("after dropped append:", events["build"])

	// nil map value: append then write back creates the key
	events["deploy"] = append(events["deploy"], "upload")
	fmt.Println("deploy:", events["deploy"])
}

What the demo shows

The map holds slice values, and every mutation goes through append, which returns a new slice header. Writing that header back with events[“build”] = append(…) is what makes the added elements visible, and the demo prints the grown slice right after.

The contrast is the dropped append: taking sp := events[“build”] and calling _ = append(sp, “forgotten”) allocates and copies but never writes the header back, so the printed map slice is unchanged regardless of spare capacity. The final lines append onto a nil map value and store the result, creating the deploy key.

Points to remember

  • A nil slice appends fine; the write-back is what creates the key.
  • Spare capacity never rescues a dropped append; only the assignment does.

Interactive Tools for This Topic

FAQ

Why can a dropped append still succeed internally?
append may extend the local slice on a copy of the header; without assigning the returned header back into the map, the map keeps pointing at the old slice and never sees the new element.