Home > Software design >  Print interface map with types
Print interface map with types

Time:12-01

I have a function that takes in some bytes, and parses them into a map. I would like to print out this map, but with the types included if possible. I tried this:

package main
import "fmt"

func main() {
   m := map[string]interface{}{
      "one": uint16(1), "two": map[string]interface{}{
         "three": uint32(3), "four": uint64(4),
      },
   }
   /*
   map[string]interface {}{
      "one":0x1, "two":map[string]interface {}{"four":0x4, "three":0x3}
   }
   */
   fmt.Printf("%#v\n", m)
}

but it doesnt print out the number types. I can do this:

// uint16
fmt.Printf("%T\n", m["one"])

but the map can be pretty big, so I would like to avoid having to manually print every value. Is it possible to do what I am wanting?

CodePudding user response:

Use for loops and recursion to print map values types:

func printTypes(m map[string]interface{}, indent string) {
    for k, v := range m {
        fmt.Printf("%s%s: %T\n", indent, k, v)

        // Recurse if value is a nested map
        if m, ok := v.(map[string]interface{}); ok {
            printTypes(m, indent "  ")
        }

    }
}

Call it like this:

printTypes(m, "")

CodePudding user response:

If you are able to control the creation of the map, you can use custom types instead:

package main
import "fmt"

type (
   Uint16 uint16
   Uint32 uint32
   Uint64 uint64
)

func (u Uint16) GoString() string {
   return fmt.Sprintf("uint16(%v)", uint16(u))
}

func (u Uint32) GoString() string {
   return fmt.Sprintf("uint32(%v)", uint32(u))
}

func (u Uint64) GoString() string {
   return fmt.Sprintf("uint64(%v)", uint64(u))
}

func main() {
   m := map[string]interface{}{
      "one": Uint16(1), "two": map[string]interface{}{
         "three": Uint32(3), "four": Uint64(4),
      },
   }
   fmt.Printf("%#v\n", m)
}

Result:

map[string]interface {}{
   "one":uint16(1), "two":map[string]interface{}{
      "four":uint64(4), "three":uint32(3)
   }
}

https://godocs.io/fmt#GoStringer

  • Related