FAQ

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

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

default:
tmpVal:=reflect.ValueOf(value)
if tmpVal.Kind() == reflect.Map{
result+="<struct>"
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()
<http://golang.org/src/pkg/reflect/value.go?s=37314:37346#L1219>.
     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>"
}
result+="</struct>"
}else{
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

Previous

Follow ups

Related Discussions

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

People

Translate

site design / logo © 2022 Grokbase