|
Color Fuzzy |
at Mar 28, 2015 at 9:22 am
|
⇧ |
| |
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!
On Saturday, March 28, 2015 at 2:46:11 PM UTC+8, Dave Cheney wrote: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 ?
On Saturday, March 28, 2015 at 1:25:00 PM UTC+8, Dave Cheney wrote: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.
On Saturday, 28 March 2015 16:15:50 UTC+11, Color Fuzzy wrote:
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!
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit
https://groups.google.com/d/optout.