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:

func serialize(value interface{}) string{

     result := "<value>"
     switch value.(type) {
     case string:
       result += fmt.Sprintf("<string>%s</string>", value.(string))
     case int:
       result += fmt.Sprintf("<int>%d</int>", value)
     case map[string]interface{}:
       result += "<struct>"
       for k, v := range value.(map[string]interface{}) {
         result += "<member>"
         result += fmt.Sprintf("<name>%s</name>", k)
         result += serialize(v)
         result += "</member>"
       result += "</struct>"
         log.Fatal("Cannot serialise: ", value)
     result += "</value>"
     return res

So, the above code is working fine if I give it map[string]interface{} as
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...
       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 | 1 of 5 | next ›
Discussion Overview
groupgolang-nuts @
postedJul 24, '14 at 7:07a
activeJul 24, '14 at 8:01a



site design / logo © 2022 Grokbase