-2

In go, is it more of a convention to modify maps by reassigning values, or using pointer values?

type Foo struct {
    Bar int
}

Reassignment:

foos := map[string]Foo{"a": Foo{1}}
v := foos["a"]
v.Bar = 2
foos["a"] = v

vs Pointers

foos := map[string]*Foo{"a": &Foo{1}}
foos["a"].Bar = 2
robbieperry22
  • 1,753
  • 1
  • 18
  • 49
  • 1
    @TimCooper, I think the question is actually distinct from [that one](https://stackoverflow.com/questions/42716852)—as it's about "the why", not "the how". – kostix Jun 04 '19 at 19:00

1 Answers1

1

You may be (inadvertently) conflating the matters here.

The reason to store pointers in a map is not to make "dot-field" modifications work—it is rather to preserve the exact placements of the values "kept" by a map.

One of the crucial properties of Go maps is that the values bound to their keys are not addressable. In other words, you cannot legally do something like

m := {"foo": 42}
p := &m["foo"] // this won't compile

The reason is that particular implementations of the Go language¹ are free to implement maps in a way which allow them to move around the values they hold. This is needed because maps are typically implemented as balanced trees, and these trees may require rebalancing after removing and/or adding new entries. Hence if the language specification were to allow taking an address of a value kept in a map, that would forbid the map to move its values around.

This is precisely the reason why you cannot do "in place" modification of map values if they have struct types, and you have to replace them "wholesale".

By extension, when you add an element to a map, the value is copied into a map, and it is also copied (moved) when the map shuffles its entries around.

Hence, the chief reason to store pointers into a map is to preserve "identities" of the values to be "indexed" by a map—having them exist in only a single place in memory—and/or to prevent excessive memory operations. Some types cannot even be sensibly copied without introducing a bug—sync.Mutex or a struct type containing one is a good example.

Getting back to your question, using pointers with the map for the purpose you propose might be a nice hack, but be aware that this is a code smell: when deciding on values vs pointers regarding a map, you should be rather concerned with the considerations outlined above.


¹ There are at least two of them which are actively maintained: the "stock" one, dubbed "gc", and a part of GCC.

kostix
  • 51,517
  • 14
  • 93
  • 176