Why can't map key be slice?

4,453 views
Skip to first unread message

Andy W. Song

unread,
Feb 9, 2012, 6:59:10 PM2/9/12
to golang-nuts
Dear list, 

I'm trying to map unicode string ([]rune) to some other type. I got this error message "invalid map key type []rune". And I found it's not rune, it's that the key can't be slice. A string is in the end a slice of bytes, why it can be map key while other slices can't?

Thanks
Andy


--
---------------------------------------------------------------
有志者,事竟成,破釜沉舟,百二秦关终属楚
苦心人,天不负,卧薪尝胆,三千越甲可吞吴

Kyle Lemons

unread,
Feb 9, 2012, 7:02:04 PM2/9/12
to Andy W. Song, golang-nuts
slices are reference types.  Strings are immutable.  I would expect that arrays can be slice keys as of Go 1, as are structs (though my memory could just be fuzzy).  Only things on which equality is defined, basically.  (note that funcs no longer satisfy this)

Andy W. Song

unread,
Feb 9, 2012, 7:02:37 PM2/9/12
to golang-nuts
Found the answer from the spec.

The comparison operators == and != (§Comparison operators
 
) must be fully defined for operands of the key type; thus thekey type must not be a struct, array or slice.
 

Andy W. Song

unread,
Feb 9, 2012, 7:03:24 PM2/9/12
to Kyle Lemons, golang-nuts
Indeed, I tried [8]rune or [3]byte, they can be map keys. 

Thanks

2012/2/10 Kyle Lemons <kev...@google.com>

Paul Borman

unread,
Feb 9, 2012, 7:08:16 PM2/9/12
to Andy W. Song, golang-nuts
That is changed in Go1.  In Go1 it can be structs as long equality is defined on each of it's elements.

spir

unread,
Feb 9, 2012, 7:17:14 PM2/9/12
to golan...@googlegroups.com
On 02/10/2012 01:08 AM, Paul Borman wrote:
> That is changed in Go1. In Go1 it can be structs as long equality is
> defined on each of it's elements.
Great!
(I thought at talking about that point precisely but refrained to avoid
beeing sent to hell once more ;-)

Denis

Reply all
Reply to author
Forward
0 new messages