Update Struct Values Stored In Maps

Struct values inside maps are not addressable: copy the value out, mutate, store back, or keep pointers in the map for one-step updates.

GoData Integrity

Code

gosnippet
31 lines
package main

import "fmt"

type Job struct {
	Name string
	Runs int
}

func main() {
	jobs := map[string]Job{
		"lint":  {Name: "lint", Runs: 3},
		"build": {Name: "build", Runs: 1},
	}

	// jobs["lint"].Runs++ 无法编译:map 值不可寻址
	// 报错:cannot assign to struct field jobs["lint"].Runs in map
	job := jobs["lint"] // 取出的是副本
	job.Runs++
	jobs["lint"] = job // 存回

	// 高频修改改存指针:一步就地更新,无整份拷贝
	refs := map[string]*Job{
		"build": {Name: "build", Runs: 1},
	}
	refs["build"].Runs++
	refs["deploy"] = &Job{Name: "deploy", Runs: 0}

	fmt.Println("value store:", jobs["lint"])
	fmt.Println("pointer store:", *refs["build"], *refs["deploy"])
}

The addressability rule

Map values are not addressable, so jobs[“lint”].Runs++ does not compile — the error is cannot assign to struct field jobs[“lint”].Runs in map. The value must be read into a local (a copy), mutated, and stored back under the same key.

The pointer alternative

refs is a map[string]*Job. Storing pointers makes one-step updates legal: refs[“build”].Runs++ mutates the shared struct through the pointer with no copy, and a new entry is added with refs[“deploy”] = &Job{…}.

Reading the output

The run prints the updated value store entry and both pointer store entries, showing that the copy path and the pointer path each end with the incremented counter.

Interactive Tools for This Topic

FAQ

Why does jobs["lint"].Runs++ fail to compile?
Map elements are not addressable in Go; the language spec forbids taking a field of a map value directly, so the increment must go through a local copy.
What does the pointer map change?
Storing *Job makes the element addressable through the pointer, so refs["build"].Runs++ mutates in place with no copy-out and copy-back.