Why need a special rule for nil map?

365 views
Skip to first unread message

Color Fuzzy

unread,
Mar 28, 2015, 1:15:50 AM3/28/15
to golan...@googlegroups.com
The rule is:
Attempts to write to a nil map will cause a runtime panic.

We can append new value to a nil slice, why we can't write new item to a nil map? Without this rule, the runtime  can just initialize a nil map when we write new item to it. Why the golang designers don't do like this? I really want to know!

Thanks!







Dave Cheney

unread,
Mar 28, 2015, 1:25:00 AM3/28/15
to golan...@googlegroups.com
append returns a new slice value, map assignment returns nothing. Map assignment is a statement, not an expression, so there is nothing to return leaving panic as the only recourse.

Color Fuzzy

unread,
Mar 28, 2015, 2:28:17 AM3/28/15
to golan...@googlegroups.com
Thanks for your reply, but I can't get the point.

I think(I am not really sure)  a map is a piece of memory block, and there is a pointer in the block, this pointer points to a hash table. If the map is nil, that pointer can only be zero(nil). 
I think(I am not really sure)  map assignment just change the the hash table. A map assignment to a nil map will panic because the hash table doesn't exist, why not just create one, and assign the address of that hash table to the map's pointer?

Dave Cheney

unread,
Mar 28, 2015, 2:46:11 AM3/28/15
to golan...@googlegroups.com
I think(I am not really sure)  a map is a piece of memory block, and there is a pointer in the block, this pointer points to a hash table. If the map is nil, that pointer can only be zero(nil). 

Pretty much, a map value is a pointer to the array of hash buckets that hold the map's data.
 
I think(I am not really sure)  map assignment just change the the hash table. A map assignment to a nil map will panic because the hash table doesn't exist, why not just create one, and assign the address of that hash table to the map's pointer?

var m map[string]int

x := m

m["hello"] = 42

fmt.Println(x["hello"])

What is printed ?

Color Fuzzy

unread,
Mar 28, 2015, 5:22:33 AM3/28/15
to golan...@googlegroups.com
Thank's very much, I got something.
The code you write will panic for nil map. I think you want to write make(map[string]int), then that code will print 42, so a map is really a pointer to a data struct. And a nil map M1 is a nil pointer, if we do M2 := M1, M1 M2 will both hold the same pointer nil. Without the special nil map rule, M1["string"] = 42 will change M1's pointer, and M2 still holds the nil pointer, that will confuse people, so they choose panic.
I think that might be the reason, thanks very much!
Reply all
Reply to author
Forward
0 new messages