I've been using map[whatever]struct{} whenever I need a set. However, I see
a few downsides to this approach:

- It's ugly. mymap["foo"] = struct{}{} looks incredibly out of place, since
almost no other Go construct uses two consecutive {} (ofc,
map[string]interface{}, but that almost always includes some values in its
initialization, not creating a second {}).
- Requires a lot of typing, and so many { and } are incredibly annoying on
most non-US keyboards since we need to hold down AltGr (and don't get me
started on not releasing the AltGr fast enough and typing U+00A0 rather
than space!).
- It's not intuitive. Neither the Go spec nor the Go Tour mention sets at
all. I mean, for most people is pretty obvious that you can use a
dictionary as a set, but most people expect a builtin set type or something
really close, so they waste time looking for it.
- It's not really documented anywhere. I can't find any references to
struct{} having == and != defined nor struct{} taking 0 bytes.
- It's not obvious. Lots of people end up using map[whatever]bool, which
wastes space.

Some interesting data from Google
Trends: http://www.google.com/trends/explore#q=golang%20set%2C%20golang%20map%2C%20golang%20slice%2C%20golang%20channel&cmpt=q

People search for "golang set" 2/3 a much as "golang channel".

What I propose is a slight modification to the language, allowing maps to
omit the value type, resulting in a set.

m := make(map[string])

This value-less map can use the same delete() function to remove values
from it. However, when it comes to inserting values I see three

1 - m["key"] = nil

I don't like this one much, but is the approach which requires the smaller
number of changes to the language. Obviously, trying to assign anything but
nil to a value-less map should generate an error.

2 - set(m, "key")

This looks good and is intuitive, but requires adding a new keyword to the
language, potentially breaking existing codebases.

3 - append(m, "key")

This does not require any new keywords, but it might give users the wrong
impression that the keys are ordered. Furthermore, it could be confusing
since slices would require slice = append(slice...) while value-less
wouldn't need the assignment.

So, what are your thoughts? Do you think map[type]struct{} is enough or
would you like some improvements in that area?


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/groups/opt_out.

Search Discussions

Discussion Posts

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 1 of 21 | next ›
Discussion Overview
groupgolang-nuts @
postedDec 6, '13 at 5:46p
activeDec 7, '13 at 9:05p



site design / logo © 2022 Grokbase