On Thursday, July 24, 2014 9:07:48 AM UTC+2, Theeraphol Wattanavekin wrote:

I am making a function that getting interface{} as parameter and have
switch type to check type.
The problem comes when I want to loop through any map with any type of
value it has.
But I found the problem that I cannot do that without type assertion.
Is there any other way to do without declaring every case of map with its
specific value types?

Here is my current code: [snip]
So, the above code is working fine if I give it map[string]interface{} as
parameter.But it won't for other map[string]anytype such as
"map[string]string", "map[string]int", etc.

I was thinking about using reflect in default case to check if it is map
and then do for loop but I got stuck there.

Below is the snippet changed from above code only "default" case

if tmpVal.Kind() == reflect.Map{
for k, v := range tmpVal { <-- I won't be able to do for loop w/o
doing type assertion correctly but I actually don't know whether map value
is int, string, float, etc...
I think you're looking for Value.MapKeys()
     for _, k := range tmpVal.MapKeys() { // Ignore index because it's a
meaningless slice index, not the map index.
         v := tmpVal.MapIndex(k)

result +="<member>"
result +=fmt.Sprintf("<name>%s</name>",k)
result += string(v)
result += "</member>"
log.Fatal("Cannot serialise: ", value)
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.

Search Discussions

Discussion Posts


Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 2 of 5 | next ›
Discussion Overview
groupgolang-nuts @
postedJul 24, '14 at 7:07a
activeJul 24, '14 at 8:01a



site design / logo © 2022 Grokbase