A type switch will clean that up a fair bit. var val interface{} var ok bool switch m := m.(type) { case m.(map[string]int): val, ok = mt.Mi[mk] case m.(map[string]i nterface{}): val, ok = mt.Mi[mk] case m.(map[string][]int): val, ok = mt.Mi[mk] case m.(map[string][]string): val, ok = mt.Mi[mk] case m.(map[string]map[string]interface{}): val, ok = mt.Mi[mk] }
But, you are working against the language. Why not just require a method `Get(k string) (interface{}, bool)` and use that? val, ok := m.Get(mk) On Mon, 2016-10-31 at 06:59 -0700, wwar...@gmail.com wrote: > I'm new to Go, and I have a question about identifying types as > they're > encountered in traversing a map[string]interface{}. > > I've ended up with a big sieve of type assertions something like > this: > > if mt.Mi, ok = m.(map[string]int); ok { > nval, ok = mt.Mi[mk] > } else if mt.MI, ok = m.(map[string]interface{}); ok { > nval, ok = mt.MI[mk] > } else if mt.Mai, ok = m.(map[string][]int); ok { > nval, ok = mt.Mai[mk] > } else if mt.Mas, ok = m.(map[string][]string); ok { > nval, ok = mt.Mas[mk] > } else if mt.Mmm, ok = m.(map[string]map[string]interface{}); > ok { > nval, ok = mt.Mmm[mk] > > mt here is a struct that performs no work; it just associates a type > to a > name, so that the run-time can see the types of the left and the > right > sides of the assignment and determine if an assignment is possible. > I > really hate looking at that statement, but all my attempts at using > reflection have failed as the compiler can't allocate with all the > possible > types that could be returned, even though in my application I only > want to > allocate for these five types. So that's my question: Can I DRY this > up? -- 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. For more options, visit https://groups.google.com/d/optout.