I seem to be regularly working with maps of stringsets and I have
found myself writing the same pattern over and over and I ended up
having my own utility function.  More importantly the syntax seems
clunky when a key doesn't exist in the map.  Is there a better way (go
idiomatically way) to write this?

import  "google3/third_party/golang/stringset/stringset"

var urlMap = make(map[string]*stringset.Set)

func collectStringsetMap(m map[string]*stringset.Set, key string,
value ...string) *stringset.Set {
  s, ok := m[key]
  if !ok {
    newset := stringset.New()  // Why can't I just use &(stringset.New()) ?
    s = &newset
    m[key] = s
  }
  s.Add(value...)
  return s
}

If there is a way to clean up the code, let me know.

Also why can map's just take a default function to construct items
that are not yet present?
Something like:

var urlMap = make(map[string]*stringset.Set, ...func =
defaultStringsetConstructor...)

func defaultStringsetConstructor(key string) *stringset.Set {
  n := stringset.New()
  return &n
}

Or perhaps some trickery in the map lookup?

 s, ok := m[key, defaultStringsetConstructor]

At the end of the day you want the map to save any new items that were
not already in the map, but I don't see any less clunky ways of doing
this.  (What am I missing?)

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAHP%2Bjq5zX69g5S88_G03CZyHMoC_xGPXxqZfbc%3DKg0FRi8%3DMgQ%40mail.gmail.com.

Reply via email to