Why append a nil slice is OK, while assign a nil map isn't OK?

5,918 views
Skip to first unread message

Nan Xiao

unread,
Mar 29, 2016, 5:11:59 AM3/29/16
to golang-nuts
Hi all,

When slice is nil, appending its value is OK:  

    var s []int
    s = append(s, 1)

But when a map is nil, assigning value is not OK, and cause panic:

    var m map[string]int
    m["Alex"] = 16

Why does golang adopt this design?

Best Regards
Nan Xiao

Dave Cheney

unread,
Mar 29, 2016, 6:33:36 AM3/29/16
to golang-nuts
It's kind of a complex question, but the shortest answer is append retuns a new sloce value, where map operations mutate and existing map value.

In the former case, you're getting a new slice value, so it's reaosnable to take a nil slice and return a non nil slice.

If mapa worked that way, map assignment would have to work like append

m = m["key"] = "value"

Which would be quite odd, to say the least.

Jesse McNelis

unread,
Mar 29, 2016, 6:48:04 AM3/29/16
to Nan Xiao, golang-nuts
map values act like pointers, so all copies of a map value point to
the same map. For keys on a nil map to be assignable you would need an
additional level of indirection, so that all the other copies of the
map value can point to the newly allocated map.

This adds an extra cost to every map lookup.

chuck bartowski

unread,
Mar 29, 2016, 9:19:43 AM3/29/16
to golang-nuts
nil map doesn't point to an initialized map. Assigning value won't reallocate point address.

The append function appends the elements x to the end of the slice s, and grows the slice if a greater capacity is needed It reallocates the resulting slice describes a completely different array.



在 2016年3月29日星期二 UTC+8下午5:11:59,Nan Xiao写道:
Reply all
Reply to author
Forward
0 new messages