-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.

5
  • Map entries do not have a fixed address as they may be moved around while the map grows/shrinks. Commented Nov 9, 2018 at 7: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? Commented Nov 9, 2018 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? Commented Nov 9, 2018 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. Commented Nov 9, 2018 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? Commented Nov 10, 2018 at 2:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.