-3
type S struct {
    e int
}

func main() {
    a := []S{{1}}
    a[0].e = 2

    b := map[int]S{0: {1}}
    b[0].e = 2 // error
}

a[0] is addressable but b[0] is not.

I know first 0 is an index and second 0 is a key.

Why golang implement like this? Any further consideration?


I've read source code of map in github.com/golang/go/src/runtime and map structure already supported indirectkey and indirectvalue if maxKeySize and maxValueSize are little enough.

type maptype struct {
    ...
    keysize       uint8  // size of key slot
    indirectkey   bool   // store ptr to key instead of key itself
    valuesize     uint8  // size of value slot
    indirectvalue bool   // store ptr to value instead of value itself
    ...
}

I think if golang designers want this syntax, it works easy now.

Of course indirectkey indirectvalue may cost more resource and GC also need do more work.

So performance is the only reason for supporting this?

Or any other consideration?

In my opinion, supporting syntax like this is valuable.

cnby
  • 389
  • 4
  • 15
  • Map entries do _not_ have a _fixed_ address as they may be moved around while the map grows/shrinks. – Volker Nov 09 '18 at 07:36
  • @Volker In this question I want to learn more about golang design between map and slice, not only the implementation. Would you please cancel the dup mark? – cnby Nov 09 '18 at 11:28
  • @icza In this question I want to learn more about golang design between map and slice, not only the implementation. Would you please cancel the dup mark? – cnby Nov 09 '18 at 11:28
  • There is nothing more to learn about Go's design of maps than what the language spec says: Entries are not addressable. For the technical why you have been given an answer. Anything why or why not this is specified is off topic for SO. – Volker Nov 09 '18 at 11:57
  • `indirectkey` and `indirectvalue` is the technical answer which golang have supported now. Or there is wrong for my understanding of the source code? – cnby Nov 10 '18 at 02:04

1 Answers1

1

As far as I known,

That's because a[0] can be replaced with address of array.

Similarly, a[1] can be replace with a[0]+(keySize*1).

But, In case of map one cannot do like that, hash algorithm changes from time to time based on your key, value pairs and number of them.

They are also rearranged from time to time.

specific computation is needed in-order to get the address of value.

Arrays or slices are easily addressable, but in case of maps it's like multiple function calls or structure look-ups ...

If one is thinking to replace it with what ever computation is needed, then binary size is going to be increased in orders of magnitude, and more over hash algorithm can keep changing from time to time.

nilsocket
  • 1,441
  • 9
  • 17